How Inheritance interacts with encapsulation?

Questions by psing2010

Showing Answers 1 - 3 of 3 Answers

There are two parts in this answer 

PART 1 : General explanation
PART 2 : OOPS concept ( JAVA )

PART 1 :

1) Inheritance is the process by which one object ( Child class or also known as sub class ) acquires the properties of another object ( Parent class ) 

Ex : Parent  ->  Child
(This is an hierarchy)
Without the use of hierarchies, each object would need to define all of its characteristics explicitly. 

Parent will be having characteristics which the child will inherit automatically.

Encapculation :A class hides everything that is not necessary for other classes to know about.


2) This shows an hierarchy.

Ex : A Bull dog is part of the classification dog, which is turn part of the mammal class, which is under the larger class animal.

Animal --> Mammals --> Dog --> Bull dog

However, by use of inheritance, an object need only define those qualities that make unique within its class. 

Ex : Bull dog class will only be having the features and characteristics which that particular bull dog possess. 
It can inherit its general attributes from its parent and so on. Thus, it is the inheritance mechanism that makes it possible for one object to be a specific instance of a more general case.

Inheritance interacts with encapsulation in this manner. If a given class encapsulates some attributes, than any subclass will have the same attributes that are possessed by its parent plus the features it adds as part of its specification.

The process goes on in this manner.

PART 2 :

2) After inheritance, in case the sub class wants to change its feature

Ex : 
Class parent 
Private color;
....
}

Class child extends parent
{
parent p=new parent();
p.color="blue";
}

output : p.color="blue" //error .. since color is private to parent class.
the features can only be inherited but couldnot be changed.

In case you want to change the feature ex: color ( As in the example )

Ex : color should be made aas "protected" (visibility)

class parent
{
protected color;
...
}
class child extends parent
{
parent p=new parent();
p.color="blue";
}

//success.

So the developers should keep in mind that the class entities should be made protected members only if there's a possibility of any additions or changes in the subsequent children class ( sub class ).

Many thanks.



Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions