Comparing Object-Oriented Languages
Shape
The Shape example creates a more complicated class structure that includes code to illustrate the object-oriented concept of inheritance. You create four separate classes: Shape, Rectangle, Circle, and TestShape. The primary purpose of this example is to illustrate how the classes are used together in the context of inheritance and how to create a primary application.
//Shape public abstract class Shape{ protected double area; public abstract double getArea(); } //Rectangle public class Rectangle extends Shape{ private double length; private double width; public Rectangle(double l, double w){ length = l; width = w; } public double getArea() { area = length*width; return (area); } } //Circle public class Circle extends Shape{ private double radius; public Circle(double r) { radius = r; } public double getArea() { area = 3.14*(radius*radius); return (area); } } //TestShape public class testShape { public static void main(String args[]) { Circle circle = new Circle(5); Rectangle rectangle = new Rectangle(4,5); } }
Listing 3a: Java Code for Shape
//Shape public abstract class Shape{ protected double area; public abstract double getArea(); } //Rectangle public class Rectangle : Shape{ private double length; private double width; public Rectangle(double l, double w){ length = l; width = w; } public override double getArea() { area = length*width; return (area); } } //Circle public class Circle : Shape { private double radius; public Circle(double r) { radius = r; } public override double getArea() { area = 3.14*(radius*radius); return (area); } } //TestShape public class TestShape { public static void Main() { Circle circle = new Circle(5); Rectangle rectangle = new Rectangle(4,5); } }
Page 4 of 5