class Human {
private String name;
private int age;
public Human(String name, int age) {
this.name = name;
this.age = age;
}
public static void message() {
System.out.println("I'm a human.");
}
}
public class Child extends Human {
public Child(String name, int age) {
super(name, age);
}
public static void message() {
System.out.println("I'm a child.");
}
public static void main(String[] args) {
Human human1 = new Human("Billy", 3);
human1.message(); //print i'm a human.
Human human2 = new Child("Billy", 3);
human2.message(); // prints i'm a human.
Child child = new Child("Billy", 3);
child.message(); // prints i'm a child.
}
}
已编辑
所以当编译器遇到: human2.message(); ,编译器是否会检查 Human 类中是否存在 message,因为 human2 的类型为 Human,当它看到 Human 类中存在该消息时,编译器会将 human2.message() 转换为 Human.message(); ??因为如果是这种情况,假设我们从 Child 类中删除 message() 方法,并且只在 main 方法中包含此代码:
Child child = new Child("比利", 3); child.message();
为什么编译器要检查 Human 类中的 message() ? (请详细解释编译器在该示例中将执行的操作)我确实知道 Child 类扩展了 Human 类,但这与静态成员有什么关系???
消息方法,当定义为静态时,是类的一部分,它们与您创建的实例(人类或儿童)无关。由于您正在定义
Human human2
,因此您正在向编译器提示使用 Human 类中的类方法。一旦您使用 Child child
作为类型定义,Java 编译器就会关联到 Child 类并使用其类方法。
在您的程序中,类 Human 继承了 Child 这允许 Child 类访问其超类 Human 中的所有方法。这是区分 message() 方法的方法。
Human human2 = new Child("Billy", 3);
human2.message(); // prints i'm a human.
上面的 human2 对象通过 Child() 构造函数访问超类 Human 的 message()
Child child = new Child("Billy", 3);
child.message(); // prints i'm a child.
上面的 child 对象通过 Child() 构造函数访问类 Child 的 message()
记住继承的概念,只有子类Child的对象才能访问超类Human
的成员Child child = new Human("Billy", 3);
child.message(); // prints i'm a human.