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
?
The only unusual aspect is that, within child class method definitions, you can't directly access parent class instance variables. For example, if the parent had a height instance variable, child class method definitions wouldn't be able to access this directly.
In short, the Child class is a child of the Parent class, and Parent (like all other Java objects) inherits from the base Java Object class.
If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java. In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding.
child class - The class that is doing the inheriting is called the child class. It inherits access to the object instance variables and methods in the parent class.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With