Can parent and child class in Java have same instance variable?

后端 未结 4 1365
说谎
说谎 2020-12-15 21:43

Consider these classes:

class Parent {
 int a;
}

class Child extends Parent {
 int a; // error?
}

Should the declaration of a

4条回答
  •  不思量自难忘°
    2020-12-15 22:18

    It's called shadowing and may cause problems for developpers.

    In your case :

    Child child = new Child();
    child.a = 1;
    System.out.println(child.a);
    System.out.println(((Parent)child).a);
    

    would print

    1
    0
    

提交回复
热议问题