We can create the reference of super class and assign the sub class object to it. The execution behavior of this reference variable is depends upon the super class. But the execution is like basic interface.
class A
|
♦-- Fun1, Fun2, FunX
|
class B
|
♦-- Fun2, FunB, FunN
|
class C
|
♦-- Fun1, FunX, Fun3
|
class D
|
♦-- FunN, FunB, Fun3
|
D d1 = new D();
d1.fun1(); //C
d1.fun2(); //B
d1.funN(); //D
C c1 = new C();
c1.funN();
c1.fun1();
c1.fun2();
A a1 = new D();
a1.fun1(); //C
a1.fun2(); //B
//a1.funN(); error
a1.funX(); //C
B b1=new C();
b1.funX(); //C
b1.funb(); //B
D d1=new A(); //Note possible
The sub class reference and super class object cannot is not possible because this object doesn't fulfill the context requirement of sub class refernece.
Write a program of dynamic polymorphism.
class AA { void AA() { System.out.println("Hello class AA method"); } } class BB extends AA { void BB() { System.out.println("Hello class BB method"); } } class CC extends BB { void fun1() { System.out.println("Hello sub class CC method"); } public static void main(String args[]) { int n=args.lenth; if(n>0) { AA.a1; int a=Integer.parseInt(args[0]); switch(a); { case 1:{ d=new AA(); break; } case 2:{ a1=new BB(); break; } case 3:{ a1=new CC(); break; } default:{ System.out.println("Invalid Arguments"); a=new AA(); break; } } a1.fun(); } else { System.out.println("Please enter arguments"); } } }
Post A Comment: