Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does inheritance technical work?

I am about to give a presentation in my company (I am a trainee) about Inheritance in Java. I think I figured it out and I also know how to use it. But one thing is not so sure. Where are the methodes stored in the storage. And how does an object know where the methodes are?

For example:

We have this class.

class Animal {
    private String desc1;
    protected String desc2;

    public void breath() {
    }

    public void eat() {
    }
}

and this class:

  class Dog extends Animal() {
        public void bark() {
        }
    }

we now make an Object of the Dog class:

Dog dog = new Dog();

So now my questions: The classes are loaded in the heap. So Dog and Animal are in the heap. (EDIT: Thats wrong, classes don't get loaded in the heap, look answers below.). So, Lets say we make dog.bark(). How does dog know where the bark method is in the Heap? Knows it where the Dog class is? Next we make dog.eat(): So when dog knows where Dog is, does Dog know where Animal is or does dog know where Animal is? With know I mean it has a address where it is on the heap. And how is it when I overwrite a method? Where is that stored?

thx for helping.

like image 665
SCBoy Avatar asked Mar 03 '11 11:03

SCBoy


1 Answers

First of all, this is JVM dependent and there is no requirement in the JLS or JVM spec on how these issues should be resolved, only that they should be resolved.

How does dog know where the bark method is in the Heap?

Usually you have what's called a Virtual Method Table, or v-table for short. You can think of this as a table mapping method identifiers, (such as bark) to function pointers. That is, if you invoke bark the VM will look into it's v-table and call the method pointed to by bark. When you extend a class and override a method, the method pointer is simply swapped to point on the overriding function.

How does dog know where the bark method is in the Heap? Knows it where the Dog class is?

Methods and classes are not stored on the heap in the same sense as instances are. Why would they?

Perhaps you have the same misconception as I had when I started with OO-programming. I thought that if I instantiate 10 Dog, I get 10 bark-methods along with it. That's not true. What you "get" when you instantiate an object, is basically it's member variables and a this reference. You can then see the this reference as an extra argument passed along when invoking a non-static methods.

like image 151
aioobe Avatar answered Oct 04 '22 09:10

aioobe