Parent class reference

Classes higher in inheritance hierarchy can point object of child classes. For example class A is parent class of class B then A class reference variable can hold reference of B class object.



Example :


class A 
{
int a;
}
class B extends A
{
void show() {System.out.println("B");}
}

class demo
{
public static void main(String ...arg)
{
A ref=new B(); // reference variable of class A and object of class B
A.show();
}
}


Important ! Using parent class reference variable members of child class can be accessed which are member of parent class.

Example :



class A 
{
int a;
}
class B extends A
{
int b;
}
class demo
{
public static void main(String ...arg)
{
A ref=new B(); // reference variable of class A and object of class B
System.out.println(ref.a); //variable a can be accessed by parent class reference variable.
System.out.println(ref.b);// variable b can't be accessed by parent class reference variable
}
}