1

What does using the casting word "(SuperClass)" do in the main method below? Does this change the object type?

class SuperClass{
  public void method(){
    System.out.print("SuperClass");
  }
}

class Sub extends SuperClass{
  public void method(){
    System.out.print("SubClass");
  }
}

public class SubSub extends Sub{
  public static void main(String args[]){
    ((SuperClass)new SubSub()).method();
  }
  public void method(){
    System.out.print("SubsubClass");
  }
}
Jeremy Levett
  • 939
  • 9
  • 13
  • It says "regard the indicated object (`new SubSub()`) as an instance of the indicated type (`SuperClass`) for this expression". In this case, it has no effect on the outcome of your program. – khelwood Dec 05 '17 at 09:29
  • Comprehensive answer for your question is already [there](https://stackoverflow.com/questions/5289393/casting-variables-in-java). – Dawid Fieluba Dec 05 '17 at 09:30

1 Answers1

3

Casting does not change the object type. It simply tells the compiler to treat the object in a different manner. That is, it changes the object reference.

Here, although the object reference is SuperClass , the object is still an object of SubSub class, so the method() of SubSub class will be called. This is also called run time polymorphism. That is, using reference of parent class to point to an object of its child class.