1

这是一个Java问题:

当实例化一个Object具有不同于该Object类型的引用类型时,确定成员可用性的方案是什么?

例如:

Shape shp = new Square(2, 4); //Where Square extends Rectangle and implements Shape

Shapeor方法会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();
}
}

当实例化具有不同于 Object 类型的 Reference 类型的 Object 时(如本例),确定成员可用性的方案是什么?

4

1 回答 1

0

Will the Shape or Square methods be associated with this code? Yes

Methods known to Shape will only be allowed to be called using shp reference variable.

Does it matter if all methods are static?

Polymorphic calls can't be made using shp reference variable if all methods are static.

Does class hiding have any bearing on the choice?

Yes, type of shp reference variable will decide exactly which method gets called. Will be decided at compile-time itself.

If methods are overridden, does that affect the choice?

Static methods are not polymorphic, so there won't exist any overriding scenario.

于 2018-10-17T19:01:56.107 回答