0

I'm learning for my java certification and I came across this piece of code.

class Feline {
    public String type = "f ";
    public Feline() {
        System.out.print("feline ");
    }
}
public class Cougar extends Feline {
    public Cougar() {
        System.out.print("cougar "); 
    }
    public static void main(String[] args) {
        new Cougar().go();
    }
    void go() {
        type = "c ";
        System.out.print(this.type + super.type);
    }
}

And when I run it, I get "feline cougar c c " so I get why it returns feline and cougar after it but why super.type refers to a Cougar object and not a Feline Object?

I saw this post but it didn't really enlightened me.

Community
  • 1
  • 1
Erunayc
  • 97
  • 1
  • 12
  • In connection with super() call check this answer as well. http://stackoverflow.com/questions/34349164/does-object-creation-of-subclass-create-object-of-superclass-if-yes-is-it-possi/34349213#34349213 – Vishrant Dec 23 '15 at 08:37
  • 1
    You changed the valud of `type`, so it got changed. What is there not to understand? – user207421 Dec 23 '15 at 08:46

4 Answers4

5

super.type is just referring to the same variable as this.type... there's only one object involved, and therefore one field.

When you create an instance of a subclass, it doesn't create two separate objects, one for the superclass and one for the subclass - it creates a single object which can be viewed as either the superclass or the subclass. It has a single set of fields. In this case, you have a single field (type) which originally had a value of "f ", but whose value was then changed to "c ".

user207421
  • 305,947
  • 44
  • 307
  • 483
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

There is just one type variable. Your Cougar's go() method sets it to "c ". Therefore both this.type and super.type print c.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

this-> invokes current class :Cougar super-> invokes Feline Feline is super class of Cougar because Cougar inherited from Feline. If you want to use Feline class fields in Cougar, You should use super.

You can see: http://www.instanceofjava.com/2015/03/this-vs-super-keywords.html

Erkan
  • 41
  • 8
1

I would like to add one more thing here for completeness

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

This constructor is translated by the compiler like this

    public Cougar() {
        super(); // Added by compiler if not added explicitly by programmer
        System.out.print("cougar "); 
    }

Thats why you get feline first and then cougar in output. Other than that,there is only one type variable involved as explained in other answers, so it is printing c for both of them.

RockAndRoll
  • 2,247
  • 2
  • 16
  • 35