-1

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?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • 1
    Why don't you try it and see? – Dawood ibn Kareem Apr 21 '14 at 21:04
  • This is called polymorphism and no you don't have to downcast. – Grammin Apr 21 '14 at 21:06
  • The volume method is defined as part of the Sphere class. Java's compiler will always use the closest method (so object, then its parent, then its parent, and so on) and won't bomb unless it cannot find a proper method. Now if Sphere did not have volume() defined, then it would go to Solid, see an abstract method, and have a problem. – Marshall Tigerus Apr 21 '14 at 21:07

2 Answers2

0

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.

Keppil
  • 45,603
  • 8
  • 97
  • 119
0
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.

tutak
  • 1,120
  • 1
  • 15
  • 28