Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Instance of Parent class using Child class Reference [duplicate]

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

like image 504
user2256009 Avatar asked Feb 06 '26 01:02

user2256009


1 Answers

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.

like image 155
mohsen kamrani Avatar answered Feb 07 '26 15:02

mohsen kamrani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!