Search code examples
javacastingtypecasting-operator

what in meaning of One o=(One) new Two(); in this programme. can anybody explain me, how this works?


class One
{
    void show1()
    {
       System.out.println("super class");
    }

}

class Two extends One
{
    static void show2()
    {
       System.out.println("subclass");
    }


}
public class Cast 
{
    public static void main(String[] args)

    {
      One o=(One) new Two();
      o.show1();

    }

}

How does this statement work in this code One o=(One) new Two(); ? Why can't I use like this Two o=(One) new Two(); ? I am confused of using casting, though o here is super class variable.. Why can't I refer sub class method using o?


Solution

  • How this statement work in this code One o=(One) new Two();

    It means that an object of class Two is created and pointed by referenc of class One. Type casting is not required.

    why can't i use like this Two o=(One) new Two();

    That is polymorphism. derived class can't point to base class.

    Rule of thumb: Base class can point to any derived class. (not vice-versa). So, you can cast a derived class to base class and not other way round.

    though o here is super class variable. why can't i refer sub class method using o.

    Right, but the actual object is of derived class and the reference is of base class. Only those methods of derived class will be accessible which are overriden in derived class.

    Try following lines of code to see yourself:

    Two obj = new One(); // Error
    One obj = new Two(); // OK
    Two obj = (Two) new One(); // Error
    

    See this: ClassCastException, ClassCastException, and Explanation of "ClassCastException" in Java