0

I'm a beginner of Java. Recently, I read this code in the Examination database. I supposed "tellName()" and "printName" that will print "base" but I got the result as below. Could you explain why I got this result? Thanks a lot.

public class Dervied extends Base{
    private String name = "dervied";
    public Dervied(){
        tellName();
        printName();
    }
    public void tellName(){
        System.out.println("Dervied tell name: " + name);
    }
    public void printName(){
        System.out.println("Dervied print name: " + name);
    }
    public static void main(String[] args){
        new Dervied();
    }
}
class Base{
    String str = "base";
    public Base(){
        tellName(); 
        printName();
    }
    public void tellName(){
        System.out.println("Base tell name: " + str);
    }
    public void printName(){
        System.out.println("Base print name: " + str);
    }
}

The result:

Dervied tell name: null
Dervied print name: null
Dervied tell name: dervied
Dervied print name: dervied
Tangii
  • 1
  • If you run your code through a debugger you will see that the `derived` constructor will call the `Base` constructor – Scary Wombat Jun 09 '22 at 06:11
  • 1
    you call your Base constructor, which calls those methods. Since you've overridden them, and you declared an execution of the child class, those methods will be called, but the str value will only be set after the constructor of Base is finished. That's why you first get nulls (for str, not name) and then the filled values – Stultuske Jun 09 '22 at 06:12
  • @ScaryWombat I'm not sure this is a duplicate. The question is, why, when the Base constructor calls those methods, it prints null. The duplicate would rather be: why is the Base constructor called – Stultuske Jun 09 '22 at 06:42
  • @Stultuske I have re-opened. I was thinking that if the OP knew that the Base constructor was called, then she would understand of course what was happening, but there again maybe not. – Scary Wombat Jun 09 '22 at 06:48
  • @ScaryWombat I think the OP believes the Base constructor not to call the overriden methods, but the ones in the Base class itself – Stultuske Jun 09 '22 at 06:50
  • @Stultuske I am sure there is a duplicate for that scenario too ;-) – Scary Wombat Jun 09 '22 at 06:53
  • Well, you have *overridable method calls* in your `Base` constructor. The method calls in the `Base` constructor don't refer to `Base::tellName` and `Base::printName`, but to the overridden `Dervied::tellName` and `Dervied::printName`. Your IDE *should* warn you about this. – MC Emperor Jun 09 '22 at 07:40

0 Answers0