Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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

Will call volume() of Sphere, sol is only a reference variable of an object(Sphere in this case) and you don't need to cast it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top