这是一个Java问题:
实例化具有与 Object
类型不同的引用类型的 Object
时,确定成员可用性的场景是什么?
例如:
Shape shp = new Square(2, 4); //Where Square extends Rectangle and implements Shape
Shape
或 Square
方法是否与此代码关联?
如果所有方法都是静态的,这有什么关系吗?
类隐藏对选择有影响吗?
如果方法被重写,会影响选择吗?
这是关于同一件事的更详细的问题:
public abstract class Writer {
public static void write() {System.out.println("Writing...");}
}
public class Author extends Writer {
public static void write() {System.out.println("Writing book");}
}
public class Programmer extends Writer {
public static void write() {System.out.println("Writing code");}
public static void main(String[] args) {
Writer w = new Programmer();
w.write();
}
}
为什么上面的代码会产生输出 -> 编写...
下面的代码产生输出 -> 编写代码
public abstract class Writer {
public void write() {System.out.println("Writing...");}
}
public class Author extends Writer {
public void write() {System.out.println("Writing book");}
}
public class Programmer extends Writer {
public void write() {System.out.println("Writing code");}
public static void main(String[] args) {
Writer w = new Programmer();
w.write();
}
}
实例化具有与对象类型不同的引用类型的对象时(如本例),确定成员可用性的场景是什么?
最佳答案
Will the Shape or Square methods be associated with this code? Yes
Shape 已知的方法只允许使用 shp
引用变量调用。
Does it matter if all methods are static?
如果所有方法都是静态的,则无法使用 shp
引用变量进行多态调用。
Does class hiding have any bearing on the choice?
是的,shp
引用变量的类型将准确决定调用哪个方法。将在编译时本身决定。
If methods are overridden, does that affect the choice?
静态方法不是多态的,因此不会存在任何覆盖场景。
关于java - 困惑 - Java 中的成员可用性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52861698/