0

Why reference variable of child class can't point to object of parent? i.e

Child obj = new Parent();

However we can do vice versa Kindly answer with memory view (heap)

2
  • This is nothing to do with memory. Commented Apr 8, 2017 at 15:43
  • 3
    There is a hierarchical relationship between object types. Every Dog is an Animal, but not every Animal is a Dog. Commented Apr 8, 2017 at 15:47

2 Answers 2

4

There is no reason which has something to do with the memory. It's much more simple. A subclass can extend the behaviour of its superclass by adding new methods. While it is not given, that a superclass has all the methods of its subclasses. Take the following example:

public class Parent {
    public void parentMethod() {}
}

public class Child extends Parent {
    public void childMethod() {}
}

Now let's think about what would happen if you could assign an instance of Parent to a variable of type Child.

Child c = new Parent(); //compiler error

Since c is of type Child, it is allowed to invoke the method childMethod(). But since it's really a Parent instance, which does not have this method, this would cause either compiler or runtime problems (depending on when the check is done).

The other way round is no problem, since you can't remove methods by extending a class.

Parent p = new Child(); //allowed

Child is a subclass of Parent and thus inherits the parentMethod(). So you can invoke this method savely.

Sign up to request clarification or add additional context in comments.

Comments

-2

The answer is too late.

I believe we can explain it in terms of memory. Maybe I'm wrong but this is what I'm thinking about this scenario.

// Assume, Required 2KB for execution
public class Parent {
    public void display(){      
        System.out.println("From Parent");
    }
}

// Total memory required for execution : 4bk
public class Child extends Parent {
    @Override
    public void display() {     
        super.display(); // 2KB
    }
    
    public void sayHello() {     
        System.out.println("From Child - Hello"); // 2KB
    }
}



   //2KB expect    //4KB assigned
     Parent parent = new Child();
        
   //4KB expect    //Only 2KB is assigning
     Child child = new Parent();

Here the 'CHILD' class variable is expecting 4KB memory, but we are trying to assign 2KB 'Parent' class objects to it. So the compiler throwing exception.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.