Assume that the following classes have been coded and compil

Assume that the following classes have been coded and compiled.

public class A { // some Java code… with a method a( )}

public class B extends A { // some java code … with a method b( ) }

public class C extends B { // some java code … with a method c( ) }

public class D extends A { // java code … with a method d( )}

public class E extends C { //…java code with a method e( ) }

Write a method named polymorph( ) which accepts a single argument that is an array of A objects. The method should walk through the array from cell 0 to cell length-1 and for each object it should execute the appropriate method (for example, if the object is of class A it should execute a( ), if it is of type B then it should execute b( ) and so on….. Hint: remember instanceOf operator.

Solution

class A {
   public void a(){
       System.out.println(\"Method of A\");
   }
}
class B extends A {
   public void b(){
       System.out.println(\"Method of B\");
   }
}
class C extends B {
   public void c(){
       System.out.println(\"Method of C\");
   }
}
class D extends A {
   public void d(){
       System.out.println(\"Method of D\");
   }
}
class E extends C {
   public void e(){
       System.out.println(\"Method of E\");
   }
}

public class Example{
   public static void main(String args[]){
       A[] a = new A[6];
       a[0] = new A();
       a[1] = new B();
       a[2] = new C();
       a[3] = new D();
       a[4] = new E();
       a[5] = new A();      
       polymorph(a);
   }
   public static void polymorph(A[] aobj){
       for(int i=0;i<aobj.length;i++){
               if(aobj[i] instanceof A){
                   aobj[i].a();
               }
               /*if(aobj[i] instanceof B){
                   aobj[i].b();
               }
               if(aobj[i] instanceof C){
                   aobj[i].c();
               }
               if(aobj[i] instanceof D){
                   aobj[i].d();
               }
               if(aobj[i] instanceof E){
                   aobj[i].e();
               }*/
       }
   }
}

/* sample output

Method of A
Method of A
Method of A
Method of A
Method of A
Method of A

*/

Assume that the following classes have been coded and compiled. public class A { // some Java code… with a method a( )} public class B extends A { // some java
Assume that the following classes have been coded and compiled. public class A { // some Java code… with a method a( )} public class B extends A { // some java

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site