使用超类初始化子类对象和反之亦然有什么区别?

pra*_*j95 6 java oop

你能告诉我这三个在用法方面的区别吗:-

Superclass p1 = new Superclass();
Superclass p2 = new Subclass();
Subclass p3 = new Subclass();
Run Code Online (Sandbox Code Playgroud)

Aif*_*ify 6

第一个和第三个分别创建声明类型的对象 - 用法是完美的,您将获得所有预期的方法。

即使您实际上有一个子类对象,第二个也只为您提供超类的功能,因为您将其声明为超类。

例如:

Superclass p1 = new Superclass(); 您的 p1 对象可以访问超类方法。

Superclass p2 = new Subclass();您的 p2 对象只能访问超类方法。该程序不知道 p2 具有特定于子类的方法,因为您将其声明为超类。

Subclass p3 = new Subclass(); 您的 p3 对象可以访问所有子类和超类方法。

使用 p2 声明方法的注意事项:给定以下类 A 和 B

public class A {
    public void print(){
        System.out.println("yyy");
    }
}

public class B extends A{
    public B() {
        super();
    }

    public void print() { // this overrides the print() method in A
        System.out.println("xxx");
    }

    public void printb() {
        System.out.println("second");
    }
}
Run Code Online (Sandbox Code Playgroud)

这发生在代码中:

public static void main(String[] args) {
    A x =  new B();

    x.print(); // prints xxx because you actually have a B object even though you have an A reference
    x.printB(); // doesn't compile. You can't call B specific methods through an A reference.
}
Run Code Online (Sandbox Code Playgroud)