我目前正在研究多态性,但我不明白以下陈述:
“类变量的类型决定了该变量可以使用哪些方法名称。 但是,由变量命名的对象决定使用具有相同方法名称的定义。”
我很困惑。
最佳答案
这意味着您可以从对象调用的方法受到该对象类型的限制。例如,假设您有以下类(class):
public class Animal {
public void sayName() {
System.out.println('animal');
}
}
public class Cow extends Animal {
@Override
public void sayName() {
System.out.println('cow');
}
public void sayMoo() {
System.out.println('mooo');
}
}
现在,您可以像这样声明您的奶牛:
Animal cow = new Cow();
您可以这样做,因为 Cow
是 Animal
的子类。但是,如果您这样做,您将无法用您的Cow
发出哞哞声,因为您已将变量创建为简单的Animal
。因此,您的变量无法访问 sayMoo
方法。
关于java - "The type of a class variable determines which method names can be used with the variable"。这意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54913181/