2

Why can we not point the Parent class object using Child class Reference.

class Abc
{
    public void Message()
    {
        System.out.println("Abc");  
    }
}

class pqr extends Abc
{
    public void Message()
    {
        System.out.println("pqr");  
    }   
}

class test1
{
    public static void main (String [] ars)
    {
        Abc a = new Abc();  
        a.Message();
        Abc b = new pqr();
        b.Message();
        pqr c = new pqr();
        c.Message();
        //pqr d =  new Abc();
    }
}

So My question is if Abc b = new pqr(); is possible then why not pqr d = new Abc();(As pqr is a child class and it will have all the features of parent class.)

I just wanted to check If I am doing d.Message() what it will print whether parent class method or child class method.

Thanks

Regent
  • 5,142
  • 3
  • 21
  • 35
user2256009
  • 169
  • 1
  • 2
  • 9

2 Answers2

12

Simple, every wolf is an animal, but not every animal is a wolf.

So Abc b = new pqr() is valid but pqr d = new Abc() is not valid.

Mohsen Kamrani
  • 7,177
  • 5
  • 42
  • 66
  • `pqr d = new Abc()` if it is not Valid as `pqr ` class is `Child class of Abc it should have ability create a Abc object also ` ? – Rookie007 Apr 18 '14 at 06:08
  • @looser> It's a different issue, composition is possible in a broad way and it's possible, but the assignment is not possible. These are two complete different notions. – Mohsen Kamrani Apr 18 '14 at 06:10
  • @looser> For example suppose every "boss" is an "employee" too. Now we can assign a boss object to an employee one. besides that in the "boss" class it may have an array of "employees" that are managed by that "boss". – Mohsen Kamrani Apr 18 '14 at 06:14
4

To explain in simple language, parents create child ( or give birth to them) child do not create parent. Since OOPs takes concepts from real world entities it is wrong for a child to create its parent.

Now coming to being technical. At compile time JAVA calls methods and properties on an object by the type of reference variable not by actual object. Actual object can be known only at runtime. So lets say you have a method in Class Pqr (please have a habit of using caps for class names) public void sayHello(). The class Pqr extends Abc. Now if Java had allowed creating parent object with child reference you would have created an object in this way

Pqr d = new Abc()

Now since type of d is Pqr, on calling

d.sayHello() 

compiler will think you are calling method from class Pqr. But on runtime in your actual object Abc there is no sayHello(). It will crash. So at compile time itself you are not allowed to create parent object with child reference. I hope this clears your doubt.

piyushtechsavy
  • 306
  • 2
  • 3