成员变量的方法覆盖
method overriding for member variable
我的理解是我们不能覆盖成员变量但是当我运行下面的程序时,我变得意外o/p
class Parent {
String message = "parent";
void say() {
System.out.println(message);
}
}
class Child extends Parent {
String message = "child";
}
public class Test {
public static void main(String[] args) {
new Child().say();
}
}
在 o/p 中,我得到“parent”,而我们正在使用子对象调用 say 方法,甚至没有 Parent 引用。
谁能帮我理解一下。
谢谢
"say"方法在parentclass上,不在child上。因此,当它调用 "message" 成员时,它会查看他自己的成员,而不是 child 的成员。通过 child class 进行呼叫的事实与此无关。
实际上,这里并没有覆盖成员变量。这是预期的行为。
编辑:
Java Language Specification 表示 "If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class."
"Inherit" 并不代表 "copy"。当你在child实例上调用"say"方法时,调用的不是"code copy"的方法,而是parentclass的方法,正如它在 parent class 中定义的那样。 parent class 对 child 变量成员一无所知。
您的 child class 扩展了 parent class 功能!所以 child class 默认有 say 方法,它的值是 (parent) 因为 parent class 当你从 [=15 调用 say 方法时会调用 say 方法=] object。如果您想改为打印 "child",则需要重写 child class 中的 say 方法并更改从 parent class 扩展的默认功能。
我的理解是我们不能覆盖成员变量但是当我运行下面的程序时,我变得意外o/p
class Parent {
String message = "parent";
void say() {
System.out.println(message);
}
}
class Child extends Parent {
String message = "child";
}
public class Test {
public static void main(String[] args) {
new Child().say();
}
}
在 o/p 中,我得到“parent”,而我们正在使用子对象调用 say 方法,甚至没有 Parent 引用。
谁能帮我理解一下。
谢谢
"say"方法在parentclass上,不在child上。因此,当它调用 "message" 成员时,它会查看他自己的成员,而不是 child 的成员。通过 child class 进行呼叫的事实与此无关。 实际上,这里并没有覆盖成员变量。这是预期的行为。
编辑:
Java Language Specification 表示 "If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class."
"Inherit" 并不代表 "copy"。当你在child实例上调用"say"方法时,调用的不是"code copy"的方法,而是parentclass的方法,正如它在 parent class 中定义的那样。 parent class 对 child 变量成员一无所知。
您的 child class 扩展了 parent class 功能!所以 child class 默认有 say 方法,它的值是 (parent) 因为 parent class 当你从 [=15 调用 say 方法时会调用 say 方法=] object。如果您想改为打印 "child",则需要重写 child class 中的 say 方法并更改从 parent class 扩展的默认功能。