在以下代码段中
class Shape {
public void area() {
System.out.println("This is Shape");
}
}
class Rectangle extends Shape {
@Override
public void area() {
System.out.println("This is Rectangle");
}
}
class Main {
public static void main(String[] args) }
Shape rect = new Rectangle();
rect.area();
// Can i force java to call Shape's area instead of Rectangle's area
// This is possible in C++ if the function is not virtual.
}
}
我可以强制java调用Shape的区域而不是Rectangle的区域吗?
编辑:不,但是为什么Java忽略了这个功能,这个功能没有指针那么危险?
答案 0 :(得分:0)
据我所知,你不能。
java中的方法调用基于您调用的对象的实际类型。在这种情况下,您调用的是实际类型为Rectangle的对象,因此调用的area()方法是Rectangle中的方法。
如果需要使用shape area()方法,则需要创建实际类型为Shape的对象。否则你永远无法在Shape中调用area()方法。 java中的反射可能有助于创建这些,因为您正在从特定类型构造更通用的类型。
答案 1 :(得分:0)
没办法,但通过改变你的超级和子类方法静态你可以实现。
public static void area(){
// Your code here
}