Within a method m in a class C, isn't this.getClass()
always C?
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
Nope:
public class C
{
public void m()
{
System.out.println(this.getClass());
}
}
public class Child extends C {}
Then:
new Child().m(); // Prints Child
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 { }
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'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With