Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Within a method m in a class C, isn't this.getClass() always C? [closed]

Tags:

java

Within a method m in a class C, isn't this.getClass() always C?

like image 777
developer Avatar asked Apr 07 '11 11:04

developer


4 Answers

No, it isn't. If there are subclasses.

class C {
   Class m() {
      return this.getClass();
   }
}
class D extends C { }

and then you can have:

C c = new D();
c.m(); // returns D.class
like image 167
Bozho Avatar answered Oct 07 '22 00:10

Bozho


Nope:

public class C
{
    public void m()
    {
        System.out.println(this.getClass());
    }
}

public class Child extends C {}

Then:

new Child().m(); // Prints Child
like image 25
Jon Skeet Avatar answered Oct 07 '22 00:10

Jon Skeet


No. Example:

public class Test {
  public static void main(String [] args) throws Exception {
    A a = new B();
    a.reportThis();
  }
}
class A { 
  public void reportThis() { 
    System.err.println(this.getClass().getName());
  } 
} 

class B extends A { }
like image 36
khachik Avatar answered Oct 07 '22 01:10

khachik


The keyword this refers to the object (instance of the class) that is in scope. It means the instance on which the method was called- which in turn means the instances of subclasses as well can be referred to by the keyword 'this'.

like image 36
Atul Avatar answered Oct 07 '22 00:10

Atul