javainheritancecompiler-errorspolymorphismdowncast

Is downcast necessary if method is abstract?


Here is an example:

public abstract class Solid{

//code...//

public abstract double volume();
}

Here is a class that extends Solid

public class Sphere extends Solid{

//code...//

public double volume(){
//implementation//
}
}

Now, if I wanted to do something like this, would I have to downcast?

public class SolidMain{

public static void main(String[] args){
Solid sol = new Sphere(//correct parameters...//);
System.out.println(sol.volume());
}

I understand that compiletime errors happen when the compiler can't find the correct method. Since the object Sol is of the type Solid, which only has an abstract volume(); method, will the compiler cause an error? Will I have to downcast Sol to a Sphere object in order to use the volume() method?


Solution

  • Will I have to downcast Sol to a Sphere object in order to use the volume() method?

    No, a Solid reference will work just fine, since the volume() method is declared there.