简体   繁体   中英

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

Consider these classes:

class Parent {
 int a;
}

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

Should the declaration of a in Child not give compilation error due to multiple declarations of int a ?

child.a shadows (or hides ) parent.a .

It's legal Java, but should be avoided. I'd expect your IDE to have an option to give you a warning about this.

Note, however, that this is only an issue because you're already exposed a variable to the world. If you make sure that all your variables are private to start with (separating out the API of methods from the implementation of fields) then it doesn't matter if both the parent and the child have the same field names - the child wouldn't be able to see the parent's fields anyway. It could cause confusion if you move a method from the child to the parent, and it's not generally great for readability, but it's better than the hiding situation.

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

Its a little bit like marrying your cousin; Legal, but not advised.

It can lead to all kinds of confusing behaviour, as the subclass declaration hides the parent class declaration.

There won't be any compilation error or runtime error.

public class Parent {
private String name;
private int age;
}

public class Child extends Parent {
String parent;
public int age;
}

Here you will be able to access child.age from Main class ... That's the only benefit you can get by having public variable for derived class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM