简体   繁体   中英

results of one of the ways to declare a new object with a parent class and a subclass

I have a Java-related question.

I have a public class Parent and its subclass public class Child extends Parent.

If I were to declare a new object as

Parent p = new Child();

would p be able to use the methods of Child and Parent? Or only Parent?

Additionally, what would be the difference in declaring p as

Child p = new Child(); 

if Child extends parent already?

It depends.

Think of it like a TV remote and a particular brand of TV.

The parent class is the older Samsung model. The child class is the newer Samsung model (and can do more things!).

If you do Parent p = new Child(); You're saying that you want to use the remote control for the older Samsung model on the new Samsung model. You're allowed to do this of course, but you won't have all the buttons to use all the new features of the Child class. Declared like this, p can access only Parent methods.

However, if you do Child p = new Child(); , then you've bought a brand new remote to go with your new tv - now you can use ALL the features of your tv. p can now access both Parent and Child methods.

Java Inheritance

class Parent
{
    public void p1()
    {
        System.out.println("Parent method");
    }
}
public class Child extends Parent {
    public void c1()
    {
        System.out.println("Child method");
    }
    public static void main(String[] args)
    {
        Child cobj = new Child();
        cobj.c1();   //method of Child class
        cobj.p1();   //method of Parent class 
    }
}

Output

Child method
Parent method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM