What happens if i assign object to another object of different class?

Ishan Trivedi :

Here is my code :

class A
{
    int x=2,y=3;
}
class B extends A
{
    //Blank 
}
public class Test
{
    public static void main(String args[])
    {
        A a=new A();
        B b;
        b=a;
        System.out.println(b.x);
        System.out.println(b.y);
    }
}

When i'm trying to run this code, "incompatible types: A can't be converted to B" Error is shown.

And also when i'm trying to type-cast "a" into "B", ClassCastException is occured.

Is there any way to assign object to another object of different class in java ?

Pelit Mamani :

Technically speaking, a variable of "base class" can be assigned "sub class" but not the other way around. Namely you can have "A a=new B()" but not "B b=new A()".

There is also an intuitive reason. The base class is usually something basic, say "Person", while the subclass is more specific and promises to provide more properties/capabilities e.g. "Teacher" (= person plus additional capabilities to teach). You can't force an ordinary Person to magically call itself a teacher, it will just fail the minute you try to activate any teaching capabilities...

We could start a philosophical argument about occasions where the specific thing has less capabilities than the base (e.g. "IncompetentPerson extends Person") but java inheritance is not generally aiming to cover that.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=108106&siteId=1