通过继承实例化

Instantiate through inheritance

I know its via inheritance when we say B c = new C(); but what is the difference with C c = new C()

我知道此代码有效,但我的流行病的原因和方式。当我自己做数学(用笔和纸)时,它给了我 80。但是当我通读 OCA 论文时,我注意到他们得出了相同的答案,但原因不同。

"When the program is run, the main() method will call the max() method in C with parameters 10 and 20 because the actual object referenced by 'c' is of class C. This method will call the max() method in B with the parameters 20 and 40. The max() method in B will in turn call the max() method in A with the parameters 20 and 40. The max() method in A will return 40 to the max() method in B. The max() method in B will return 80 to the max() method in C. And finally the max() of C will return 80 in main() which will be printed out."

这对我来说听起来或多或少是希腊语,请帮忙。想知道写 B c = new C(); 是什么意思以及它与 C c = new C();

的区别

如果您写成 B c = new C();,由于动态绑定,结果将相同。在运行时,对象类型将用于解析要调用的方法。 c (C) 的对象类型仍然相同,所以没有区别。

代码中的唯一区别是引用的类型发生了变化。

假设我们有 C c = new C(); B b = c;

一个C object 被构建了,但是你只能通过b 看到它的B 部分。就像不同的人对你的看法不同:例如,你的朋友将你视为朋友,但你的 parent 将你视为 child 即使是同一个人(你是独一无二的,但人们看到你不同)。然后通过 b 与此 object 交谈仅允许与它的 B 愿景交谈(仅在 B 中定义为 public 的内容)。当然,object 是一个 C,那么如果您在其上使用 B 方法,那么它的 C 行为就是答案。这被称为多态性(不同的外观对于单个object)通过子类型化(外观通过包含相互关联)。

这种用法的真实示例如下。我想你同意 CarVehicule,因为 VanVehicle。然后,当您建造停车场时,您不仅为汽车设计了它,还为任何 Vehicle 设计了它,因为您可以停放 CarVan。所以看到一个Car或一个Van作为一个简单的Vehicle.

是非常有用的

在 java 这可能会给出:

class VehicleThatCouldBeParked {}
class Car extends VehicleThatCouldBeParked {}
class Van extends VehicleThatCouldBeParked {}

...
VehicleThatCouldBeParked []parking = ne VehicleThatCouldBeParked[100]; // build a parking with hundred locations
...
Car myCar = new Car(); // some car
...
Van myVan = new Van(); // some van
...
parking[76] = myCar; // my car is parked in slot 77
parking[34] = myVan; // my van is parked in slot 35
...

这在许多情况下(甚至在现实生活中)非常重要,无需注意 objects 的一些细节。

在运行时,将调用实际对象的方法。

然而,差异取决于您的使用情况,您可能有 B 定义行为和 C,并且为了回答 D、E 和 F 可能以特定方式实现它。现在使用 B 类型的引用,您可以为客户创建一个通用合同。

建议阅读互联网上大量资源中的基本 OOP 概念。

您关心的问题是关于多态性的。如果你有变量(把它想象成一个盒子)指向 class(我们称之为 A),指向一些 class,你可以在这个盒子里放任何 class扩展 A.

关于你进一步的问题,我建议仔细阅读post: Casting objects in Java

abstract class A {
    protected abstract void print();
}

class B extends A {

    @Override
    protected void print() {
        System.out.println("I am in B");
    }

    public void print1() {
        System.out.println("No in A");
    }
}

class C extends A {

    @Override
    protected void print() {
        System.out.println("I am in C");
    }

    public void print1() {
        System.out.println("No in A");
    }
}

A a = new C(); a.print();

//a.print1(); can't resolve method print1()

//B b = new C(); incompatible type