1

Question: The result of the following code is "5 A" and "10 B". How is it possible that for b.print(), this.num is a reference to a Class A object and this.getClass() is a reference to a Class B Object?

Superclass A

public class A {
  private int num;

  public A(int num) {
    this.num = num;
  }

  public void print() {
    System.out.println(this.num + " " + this.getClass().getName());
  }
}

Subclass B

public class B extends A {

  public B(int num) {
    super(num);
  }
}

Main Method

A a = new A(5);
B b = new B(10);
a.print();
b.print();
Pablo Matias Gomez
  • 6,614
  • 7
  • 38
  • 72
hasNoPatience
  • 67
  • 2
  • 4

2 Answers2

0

These are two distinct things.

this.getClass() or more simply getClass() (as this is implied as not specified) will always refer to the actual runtime class that may be the class that uses it or a child of it. If you call it from A, it will return the A class but if you call it from a child of it, it will return this child class.

While this.num refers to a specific instance field declared in the A class.
When you code refer to this field, it relies necessarily on the class that declares this specific field.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
0

Whenever you call this in an instance, you are going to be calling the actual instance, and not the "class". For example, in you case, if you override the method print in your class B, like this;

public class B extends A {

    public B(int num) {
        super(num);
    }

    public void print() {
        System.out.println("PRINTING B");
    }
}

Then when you call the print method it will call this one and not the parent one, even if you use this.print() inside any method of the class A

If you really want to explicitly print the A class, then you need to reference it like this:

    public void print() {
        System.out.println(this.num + " " + A.class.getName());
    }
Pablo Matias Gomez
  • 6,614
  • 7
  • 38
  • 72