Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance and the "this" keyword

Suppose that we have next situation:

Parent class A:

class A{  
    public A(){}
    public doSomething(){  
        System.out.println(this.getClass());
    }
}

with a child class B:

class B extends A{  
    public B(){}
    public void doSomething(){
        super.doSomething();
        System.out.println(this.getClass());
    }
}

and Main class:

class Main{  
    public static void main(String[] args){
        A ab=new B();
        ab.doSomething();
    }
}

When I execute this code result is

B  
B

Why does this, referenced in superclass A, returns B as a class when the reference is of type A?

like image 816
slomir Avatar asked Mar 01 '11 14:03

slomir


1 Answers

It doesn't matter what the reference is, it's the instantiated object's class that counts. The object that you're creating is of type B, therefore this.getClass() is always going to return B.

like image 199
Tom Jefferys Avatar answered Sep 19 '22 20:09

Tom Jefferys