0

Can any one please help me in understanding the output.

public class A { 
    public A() { 
        this.print(); 
    }

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

Class B extending class A:

public class B extends A { 
    int i; 

    public B() { 
        i=4; 
    }
        
    @Override
    public void print() {
        System.out.println("calling B.print");
        System.out.println(i);
    }

Finally creating object of class B

public class Tester { 
    public static void main(String[] args) { 
        A obj = new B(); 
        obj.print(); 
    } 
}

Output:

calling B.print
0
calling B.print
4

Shouldn't this.print() from inside A() constructor call A's method()?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • No, it should not. The object in question is of type `B`, even during the constructor call of `A`, so the method in `B` is called. – Mark Rotteveel Jan 13 '23 at 15:49
  • When you call `new B();` you are creating *instance of `B` class*. Contrary to what most people believe, part responsible for *creating* that instance is **`new B`**. The following `()` of `new B ()` just tells compiler which constructor of class B it should use to *set up that **already created** instance of `B`* - because currently all fields of that instance are set to hold default values (0 for numeric types, false for boolean, null for reference types, etc.). In constructor we can access *that* instance via `this` like `this.print()`, it doesn't matter if it is called in A or in B. – Pshemo Jan 13 '23 at 16:07
  • Now since you called `new B()` the parameterless constructor was called `public B() { i=4; }`. BUT lets not forget that at start of all constructors (except of `java.util.Object` since it doesn't have super type) there is implicit/explicit call to `super` class - in this case `super()` which will execute code of `public A() { this.print(); }` from `A` class. Note that this happens before `i=4` is executed, so `i` still holds its default value 0. Since in `A` class you call `this.print()` (or even `print()` without `this.`) the *dynamic-binding* checks type of `this` instance. – Pshemo Jan 13 '23 at 16:13
  • And it is B so JVM will start searching for *code* of `print` in B class. That is how polymorphism works. – Pshemo Jan 13 '23 at 16:13

0 Answers0