Inheritance in Java – something I can’t understand

I have questions about inheritance in Java, which I can't understand:

I have two classes:

public class C
{
    public void foo(D d)
    {
         System.out.println("cd");  
    }
}

public class D extends C
{
    public void foo(C c)
    {
         System.out.println("dc");  
    }

    public void foo(D d)
    {
         System.out.println("dd");  
    }
}

Main:

public static void main(String[] args)
{
    C cd = new D();
    D dd = (D)cd;   
}

What is the type of each CD and DD? Why?

Solution

There are two different types involved:

>Type of variable; > The type of object referenced by the variable

The type of a variable is independent of the type of object it currently refers to – and vice versa, the type of object is independent of the type of variable accessing it Therefore, when you assign an object to a different variable, its type is not affected

So,

>The type of variable CD is C; > The type of object it references is d

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>