Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 468
user421814 Avatar asked Aug 17 '10 09:08

user421814


People also ask

Can child class access instance variables of parent class?

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.

Is the child class instance an instance of the parent class?

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.

What happens if parent and child class have same method?

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.

Does a child class inherit instance variables?

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.


2 Answers

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.

like image 187
Jon Skeet Avatar answered Oct 13 '22 00:10

Jon Skeet


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
like image 38
Colin Hebert Avatar answered Oct 12 '22 23:10

Colin Hebert