max muster
max muster

Reputation: 31

How is the memory management in polymorphism?

How is something like this saved in memory(like stack, heap etc.)?

public class Animal {
    // Stuff
}

public class Dog extends Animal {
    // Stuff
}

public class Test {
    public static void main(String[] args) {
        Animal bello = new Dog();
    }
}

how is this: Animal bello = new Dog(); managed in terms of memory? How is this saved in memory when bello is a reference of type Animal but the objects it's pointing to is of type Dog

Upvotes: 2

Views: 1266

Answers (2)

Omar Essam El-Din
Omar Essam El-Din

Reputation: 1873

Simply Parent(base) class will point to its Child extending it , and assigning its parent properties & methods implementation from the way that child implementing it

   //parent class
   public class Animal {
        int x = 5;
        int y = 5;
        void fun() { return "from Animal";}
    }

   //child class
    public class Dog extends Animal {
        //constructor
        Dog( ) {   x++; }

        @override
        void fun() { return "from Dog";}
    }
    
    public class Test {
        public static void main(String[] args) {
            Animal bello = new Dog();

            bello.fun(); //return "from Dog"
            bello.x ; //6
            bello.y ; //5
        }
}

I hope this diagram explains it well

enter image description here

Upvotes: 0

Christophe
Christophe

Reputation: 73530

Java defines classes as reference types. The Java specifications explain how this works:

4.3.1 Objects
An object is a class instance or an array.
The reference values (often just references ) are pointers to these objects, and a special null reference, which refers to no object.

The language completely hides this implementation detail, but a reference is a value that is passed (as parameter or as local variable on the the stack, or as object field in the heap) and that allows to find the real object in memory (in the heap). So when you write:

    Animal bello = new Dog();

the JVM will allocate a Dog object in heap memory and new will return the reference to find it. The assignment just copies the reference into bello local variable (the compiler will of course have checked that the types are compatible).

The trick then is in the object layout.To make it simple, the object keeps a track of its real class. The compiler will produce an astute layout where the layout of a Dog object is a an extension to the Animal layout. When you call a method, the method corresponding to the real object's class will then be called. Of course, in reality, all this is a little more complex.

Upvotes: 1

Related Questions