0

i´m still learning Java (and this is my first question on SO), so please forgive me if this kind of question is misplaced here or if my wording isn´t correct!

I´m looking into inheritance and polymorphism at the moment and weren´t able to answer the following question of mine, despite googling quite a few.

public class Animal {
    public String name = "Bello";

}

public class Cat extends Animal {
    public String name = "Kitty";

    public static void main(String[] args) {

        Cat cat1 = new Cat();
        Animal animal1 = cat1;
        System.out.println(cat1.name);
        System.out.println(animal1.name);
    }
}

System.out.println(cat1.name); prints out Kitty, but System.out.println(animal1.name); prints out Bello

So apperently the value of the attribute name gets changed as the instance of the child class is saved as an object of the parent class. Why does the parent class change the value into her own default-value, even it is already set in cat1? Seems there is sth. to know which i wasn´t able to figure out..

TobiDoe
  • 103
  • 1
  • 5
  • 1
    This is called _shadowing_; you have _two separate fields_ each named `name`. You're accessing different fields based on the compile-time type of the variables. – chrylis -cautiouslyoptimistic- Jan 05 '20 at 00:41
  • The concept is known as [field -or attribute-hiding](https://docs.oracle.com/javase/tutorial/java/IandI/hidevariables.html). It is part of Java's inheritance model. In general, it is regarded as "bad practice" to hide fields. – Turing85 Jan 05 '20 at 00:42

1 Answers1

1

Variable with same name in parent and sub-class is known as variable hiding. But subclass will have access to both properties.

Access it using this and super keyword shown in below modified code

class Animal {
    public String name = "Bello";

}

public class Cat extends Animal {
    public String name = "Kitty";

    Cat(){
        System.out.println(this.name); //Kitty
        System.out.println(super.name); //Bello
    }

    public static void main(String[] args) {

        Cat cat1 = new Cat();
        Animal animal1 = cat1;

        System.out.println(cat1.name);
        System.out.println(animal1.name);
    }
}
Sarjit
  • 799
  • 7
  • 9