As part of the m method in class C, is this not this.getClass () always C?

As part of the method m in class C, is not this.getClass() always C?

+6
source share
4 answers

No, it is not. If there are subclasses.

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

and then you can:

 C c = new D(); cm(); // returns D.class 
+12
source

Nope

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

Then:

 new Child().m(); // Prints Child 
+8
source

Not. 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 { } 
+2
source

The this keyword refers to an object (an instance of a class) that is in scope. This means the instance that the method was called on, which in turn means that subclasses can also refer to the keyword 'this'.

+1
source

Source: https://habr.com/ru/post/885404/


All Articles