user3369935
user3369935

Reputation: 63

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?

Upvotes: -1

Views: 457

Answers (3)

Corvus-OS
Corvus-OS

Reputation: 1

If you had some other method defined in the Sphere class that is not present in its parent class(Solid) such as

public class Sphere extends Solid{

//code...//

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

public void extraFeature(){ //something extra }

sol object can use extraFeature method as it implictly downcasts itself from Solid class to Sphere class

However,It wouldn't have down-casted if Solid class wasn't an abstract class and you would need to manually do it by:

public class SolidMain{

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

Upvotes: 0

tutak
tutak

Reputation: 1098

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.

Upvotes: 0

Keppil
Keppil

Reputation: 46239

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.

Upvotes: 0

Related Questions