dcsimg
July 8, 2020
Hot Topics:

Comparing Object-Oriented Languages

  • By Matt Weisfeld
  • Send Email »
  • More Articles »

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);

   }

}

Listing 3b: C# Code for Shape





Page 4 of 5



This article was originally published on December 6, 2007

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.


Thanks for your registration, follow us on our social networks to keep up-to-date