قراءة
عرض

Example

Define a base class called Polygon which has two integer attributes represent width and height of a Polygon. Set method is used for setting the width and the height. Derive three subclasses Rectangle, Triangle and Parallelogram. Write a main class to print the areas of the three Polygons using one polygon object. The output looks like:

20

rectangle

4 5

28

triangle

7 8

30

paralleloram


5 6

public abstract class Polygon {

protected int d1,d2;

public void set(int a,int b){

d1=a;d2=b;}

public abstract int area();

public abstract void print();

}

public class Rectangle extends Polygon{

public int area(){return (d1*d2);}

public void print(){


System.out.println("rectangle");

System.out.println(d1+" "+d2);

}

}

public class Triangle extends Polygon {

public int area(){return (d1*d2/2);}

public void print(){

System.out.println("triangle");

System.out.println(d1+" "+d2);

}

}


public class Parallel extends Polygon {

public int area(){return (d1*d2);}

public void print(){

System.out.println("parallelogram");

System.out.println(d1+" "+d2);

}

}

Re write the previous main method using array to store the three polygons.

Public class Main{

public static void main(String[] args) {

Polygon [] a=new Polygon[3];


for (int i=0;i<3;i++)

switch (i) {

case 0: a[i]=new Rectangle();a[i].set(5,4);break;

case 1: a[i]=new Triangle();a[i].set(7,8);break;

case 2: a[i]=new Parallel();a[i].set(5,6);break;

}

for(int i=0;i<3;i++){

System.out.println(a[i].area());

a[i].print();}

}

}


The output is:

20

rectangle

5 4

28

triangle

7 8

30

paralleloram

5 6



رفعت المحاضرة من قبل: HS Alqaicy
المشاهدات: لقد قام 0 عضواً و 158 زائراً بقراءة هذه المحاضرة








تسجيل دخول

أو
عبر الحساب الاعتيادي
الرجاء كتابة البريد الالكتروني بشكل صحيح
الرجاء كتابة كلمة المرور
لست عضواً في موقع محاضراتي؟
اضغط هنا للتسجيل