All about Super class reference & sub class object

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.

Super class reference & sub class object
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");
  }
 }
}
Axact

Narendra

Hello, everyone! I am Narendra Bagul founder of Javanotes9. First of all thank you for visiting my blog. Hope you all like my java notes as well. I'm young part time blogger and a Computer Engineering student. I started blogging as a hobby. Now here I'm sharing my little acquired knowledge about my favorite programming language JAVA.

Post A Comment: