-4

I think the output should be "cougar c f", since calling Cougar() should just print cougar and call to go() should print 'c' for this.type and 'f' for super.type, since super keyword is used to call the parent class. Can anyone please verify this?

class Feline {
    public String type = "f ";

    public Feline() {
        System.out.print("feline ");
    }
}

class Cougar extends Feline {
    public Cougar() {
        System.out.print("cougar ");
    }

    void go() {
        type = "c ";
        System.out.print(this.type + super.type);
    }

    public static void main(String[] args) {
        new Cougar().go();
    }
}
Manish Joshi
  • 85
  • 2
  • 12
  • *but it shows incorrect* ? what shows it as incorrect? ... If you simply execute it in an IDE. You would get the result. – Naman Dec 12 '18 at 10:49
  • 1
    What are you asking.... – SamHoque Dec 12 '18 at 10:49
  • I guess this is a question from some exam/certification, is this correct? – Hulk Dec 12 '18 at 11:00
  • In that case, just a hint: what is implicitly called in the first line of each constructor? – Hulk Dec 12 '18 at 11:02
  • @Hulk you are right, this is a sample question for oracle. And the super constructor is called implicitly in the first line of each constructor. Thank you very much. – Manish Joshi Dec 12 '18 at 11:30
  • @Hulk but why is `super.type` returning 'c', when it should be 'f', the `type` in parent class? – Manish Joshi Dec 12 '18 at 11:51
  • 1
    @ManishJoshi there is only one `type`, and it is assigned a new value in the first line of `go()`. I.e. `this.type` and `super.type` refer to the same field - one of the reasons to avoid public fields is that they can cause such confusion. – Hulk Dec 12 '18 at 11:59
  • @Hulk Got it. Thanks! – Manish Joshi Dec 12 '18 at 12:31

1 Answers1

1

So the quick answer, the output will be

feline cougar c c

The reason now.

new Cougar() will create an instance Cougar, since a Cougar is a Feline, Feline's constructor is the first thing called in the Cougar's constructor. This explain "feline cougar".

public Cougar() {
    System.out.print("cougar ");
}

is actually looking like

public Cougar() {
  super(); //printing "Feline"
    System.out.print("cougar ");
}

Now, this.type and super.type both access the same variable declared in Feline.

Since you assign "c" to it, this explain the output "c c"

AxelH
  • 14,325
  • 2
  • 25
  • 55