For example:
I have customer
class which has two child classes, which are guest
class or signed-up users
class. Customer class
has username
as an instance variable. Does guest class
also have username
as an instance variable? How about methods
of customer class?

- 109
- 1
- 2
- 6
-
The answers: It depends, and it depends, respectively. – J Steven Perry Oct 01 '14 at 20:56
-
@JStevenPerry can you explain it further? what does it depend on? – Hiep Oct 01 '14 at 21:02
2 Answers
Inheritance in Java is always complete, in the sense that all attributes and methods will exist in the child class. Those that were declared in the "super" class as private will not be visible in a subclass, although they will still be there.
If you're thinking about some sort of partial inheritance, the best thing you can do is rethink your class model: create a different base class that can be applied to all particular cases (so that if you have a username
attribute in the Customer class, you must be sure that all customers will have one). If you don't want Guest objects to have that attribute, simply remove it from Customer and declare it in your SignedUpCustomer class. Java interfaces may also be useful in other occasions.

- 27,810
- 13
- 101
- 139
The Guest class and SignedUpUsers class will inherit all the class members (methods and variables) from the Customer class that do not have their access level marked as 'private' or default (no access level specified).
So in your example, if username variable has access level public or protected, then it will be inherited. The same goes for all your methods.
String username; // will not be inherited
private String username; // will not be inherited
protected String username; // will be inherited
public String username; // will be inherited

- 7,378
- 1
- 27
- 32
-
1Actually, they're all physically inherited (the methods are in the method table of the subclass), but some are inaccessible (making the fact that they're inherited moot). And "default" access depends on the package. – Hot Licks Oct 01 '14 at 21:06