这是一个例子:
public abstract class Solid{
//code...//
public abstract double volume();
}
这是扩展Solid的类
public class Sphere extends Solid{
//code...//
public double volume(){
//implementation//
}
}
现在,如果我想做这样的事情,我是否会灰心?
public class SolidMain{
public static void main(String[] args){
Solid sol = new Sphere(//correct parameters...//);
System.out.println(sol.volume());
}
我了解,当编译器找不到正确的方法时,就会发生编译时错误。由于对象
Sol
的类型为Solid
,它仅具有abstract volume();
方法,因此编译器会导致错误吗?为了使用Sol
方法,我是否必须将Sphere
转换为volume()
对象?
最佳答案
Will I have to downcast Sol to a Sphere object in order to use the volume() method?
不可以,因为在这里声明了
Solid
方法,所以volume()
引用可以正常工作。
关于java - 如果方法是抽象的,是否需要向下转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23205997/