dcsimg
October 17, 2018
Hot Topics:

Comparing Object-Oriented Languages

  • December 6, 2007
  • 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



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

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

By submitting your information, you agree that developer.com may send you developer offers via email, phone and text message, as well as email offers about other products and services that developer believes may be of interest to you. developer will process your information in accordance with the Quinstreet Privacy Policy.

Sitemap

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