简体   繁体   中英

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

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 .

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

   public class Animal {
        int x = 5;
        int y = 5;
        void fun() { return "from Animal";}
    }
    
    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
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM