1.Can Some one illustrate how it works? Why it prints 1 instead of 2?
2.From the Oracle Official Java tutorial, the definition of this
: Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
// Base Class
class A {
public int m = 1;
public void view(){
// Print variable m
System.out.println(this.m);
//print the current class name
System.out.println(this.getClass());
}
}
// Subclass extends Base Class
public class B extends A{
// Define another variable m
public int m = 2;
public static void main(String[] args) {
B b = new B();
b.view();
}
}
Below is the debug of the view(){}:
My Question is:
You can see the current object is B, when we usethis
, it represents the B
, m = 1 in base class A, m = 2 in derived class B, then use the this.m
, it should print 2, isn't it?