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

StackOverflow https://stackoverflow.com/questions/14723089

Вопрос

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?

Это было полезно?

Решение

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

Другие советы

Variable on the right side should of same type (or any subtype ) that of on the left side.

One o=(One) new Two();

Here Two is subtype of One so it can casted to One and can be used with reference variable of type One.

 Two o=(One) new Two();

Here you can cast object of type Two to One which is upcasting but you cant assign same casted object to reference variable of type Two because One is not a subclass of Two.

Given hierarchy is

One      
 |--> Two   

Two can be used in place of One as it under One (sub type of One) in hierarchy but you cant do vice versa.

How this statement work

One o=(One) new Two();

Object of type Two is created on the heap. But reference o is cast to be reference to type One

Actually you can do:

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

Because Two would also have show1 method.

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

Reference mismatch. But you can do this

Two o=(Two)(One) new Two();

why can't i refer sub class method using o.

Here show2 method is only present in subclass and it is not present in superclass and your object o is of derived class but you have to override method in derived class so you can't access show2.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top