| Author |
does inheritance break the encapsulation or data hiding?
|
Anil Deshpande
Ranch Hand
Joined: Jan 13, 2008
Posts: 117
|
|
This is a conceptual person.
Say I have Class1(with private method1) and Class2 extending Class1 and tries to override. And Conceptually you can't override private method. Because private methods are basically not inherited and thus can not be overridden.
The code looks like this
But Now looks at this code
HOW class2 has "a" as instance variable. It's private and getA() should create a problem?
But it works perfectly fine. Its prints the value of a as 10. How come Class2 for access to "a" even though its private instance variable of its super class Class1.
Isn't it against the object orientation?
does inheritance break the encapsulation or data hiding?
OR AM I MISSING SOME THING
|
Anil Deshpande
SCJP 1.5, SCWCD 1.5
|
 |
Bert Wilkinson
Ranch Hand
Joined: Oct 28, 2009
Posts: 33
|
|
Yes.....You are missing something.
When you extend a class, you are extending all the methods in that class as well. So, any object of type Class2 in your example has full access to anything that an object of Class1 would have. So, in your example, your class2 object behaves as if it is a member of both Class1 and Class2, because it extends Class1.
This is the clear definition of inheritance, and does not break encapsulation rules.
|
 |
shivendra tripathi
Ranch Hand
Joined: Aug 26, 2008
Posts: 263
|
|
|
You are calling a method which you have declared as public. Try doing new Class1.a inside TestClass you will get error. Now modify the access modifier of a as public and try Class1.a it will work.
|
SCJP 1.5(97%) My Blog
|
 |
Jim Hoglund
Ranch Hand
Joined: Jan 09, 2008
Posts: 525
|
|
Class1 is well encapsulated if all its member variables are declared
private, so they can be accessed or changed only by method calls.
Regarding your first sample code, a child class inherits all the parent
member variables and methods that it can see; those with public,
protected and often package access. In this case, Class2 cannot see
method1() of its parent, so Class2 is free to define a similar method.
As you said, this is not an example of overriding.
Jim ... ...
|
BEE MBA PMP SCJP-6
|
 |
Anil Deshpande
Ranch Hand
Joined: Jan 13, 2008
Posts: 117
|
|
|
Thanks a lot for the replies.
|
 |
 |
|
|
subject: does inheritance break the encapsulation or data hiding?
|
|
|