Consider these classes:
class Parent {
int a;
}
class Child extends Parent {
int a; // error?
}
Should the declaration of a
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
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.
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