Java 如果方法是抽象的,是否需要向下转换?

Java 如果方法是抽象的,是否需要向下转换?,java,inheritance,compiler-errors,polymorphism,downcast,Java,Inheritance,Compiler Errors,Polymorphism,Downcast,以下是一个例子: public abstract class Solid{ //code...// public abstract double volume(); } 下面是一个扩展了Solid的类 public class Sphere extends Solid{ //code...// public double volume(){ //implementation// } } 现在,如果我想做这样的事情,我会沮丧吗 public class SolidMain{ publ

以下是一个例子:

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
类型,它只有一个
抽象卷()方法,编译器是否会导致错误?为了使用
volume()
方法,我必须将
Sol
向下投射到
Sphere
对象吗

为了使用volume()方法,我必须将Sol向下投射到球体对象吗

不,一个
Solid
引用可以正常工作,因为
volume()
方法在那里声明

System.out.println(sol.volume());

将调用Sphere的volume(),sol只是对象(本例中为Sphere)的一个引用变量,您不需要强制转换它。

为什么不试试看呢?这称为多态性,不需要强制转换。volume方法定义为Sphere类的一部分。Java编译器将始终使用最接近的方法(对象、其父对象、其父对象等等),除非找不到合适的方法,否则不会爆炸。现在,若Sphere并没有定义volume(),那个么它将转到Solid,看到一个抽象方法,并出现问题。