A)你不能在这个意义上覆盖字段。字段“不是虚拟的”方法。
fields cannot be overridden but they can be hidden ie if you declare a field in a subclass with the same name as one in the superclass, the superclass field can only be accessed using super or the superclasses type
B)如果可以的话,这个领域可能不得不至少受到保护:-)
since object won’t be created for super class (as it is abstract)
实际上是实例化的。
抽象关键字只能确保在实例化时,它以子类的形式实例化。当实例化一只狗时,你同时实例化一只动物!因此,在动物背景下的这个参考将总是指一只狗或一只猫或其他任何东西,但在所有情况下它都是指一些动物。 🙂
如下面的示例所示,即使在抽象类中,此引用也是有意义的:
abstract class Animal {
public String name;
public Animal(String name) {
System.out.println("Constructing an Animal");
this.name = name;
}
public abstract void speak();
}
class Dog extends Animal {
public Dog(String name) {
super(name);
System.out.println(" Constructing a Dog");
}
public void speak() {
System.out.println("Bark! My name is " + name);
}
}
public class Test {
public static void main(String... args) {
new Dog("Woffy").speak();
}
}
打印:
Constructing an Animal
Constructing a Dog
Bark! My name is Woffy
更新:此引用引用与超类中与子类中相同的对象。
你可以尝试添加
public Animal getSuperThis() { return this; }
到动物类,做
System.out.println(this == getSuperThis());
在Dog.speak()中。你会看到它打印真实。