Example of polymorphism in java with abstract class

Ads:

Best selling and shopping at: ebay

free Download unlimited wallpaper at: Photoshare.byethost3.com


Program definition:

Write a program to create abstract class shape having instance variables dim1(dimension) in double and color and two member methods: 1.void display():displays the color of the specific shape. 2.abstract void area(): gives the area for given shape.

Note:

A method for which you want to ensure that it must be overridden(In following example area()),you can define such method as abstract methodand class that contains one or more abstract method must be abstract class.Just put keyword abstract to define it as abstract class

abstract class shape
{
 private double dim1;
 String color;
 shape(double d1,String c)
 {
  dim1=d1;color=c;
 }
 void display()
 {
  System.out.println("Color :"+color);
 }
 abstract void area();
 public double getdim1(){return(dim1);}
}
class triangle extends shape
{
 private double dim2;//dim1=base,dim2-altitude
 triangle(double d1,double d2,String c)
 {
  super(d1,c);
  dim2=d2;
 }
 void area()
 {
  double d1=getdim1();
  double a;
  a =d1*dim2/2;
  System.out.println("Area :"+a);
 }
}
class square extends shape
{
 
 square(double d1,String c)
 {
  super(d1,c);
 }
 void area()
 {
  double d1=getdim1();
  double a=d1*d1;
  System.out.println("Area :"+a);
 }
}
class rectangle extends shape
{
 private double dim2;//dim1=width,dim2=breath
 rectangle(double d1,double d2,String c)
 {
  super(d1,c);
  dim2=d2;
 }
 void area()
 {
  double d1=getdim1();
  double a= d1*dim2;
  System.out.println("Area :"+a);
 }
}
class circle extends shape
{
 
 circle(double d1,String c)
 {
  super(d1,c);
 }
 void area()
 {
  double d1=getdim1();
  double pi=3.1416;
  double a= 2*pi*d1;
  System.out.println("Area :"+a);

 }
}
class a9
{
 public static void main(String args[])
 {
  triangle t = new triangle(2,4,"red");
  t.display();
  t.area();
  square s = new square(4,"green");
  s.display();
  s.area();
  rectangle r = new rectangle(4,8,"yellow");
  r.display();
  r.area();
  circle c = new circle(6,"orange");
  c.display();
  c.area();
 }
}

For more Assignment problems Click Here


See Also:

1 comment: