Java inheritance, composition, encapsulation and polymophism

Composition means HAS A
Inheritance means IS A

Example: Car has a Engine and Car is a Automobile

In programming this is represented as:

 1 class Engine {} // The engine class.
 2 
 3 class Automobile{} // Automobile class which is parent to Car class.
 4 
 5 // Car is an Automobile, so Car class extends Automobile class.
 6 class Car extends Automobile{ 
 7 
 8  // Car has a Engine so, Car class has an instance of Engine class as its member.
 9  private Engine engine; 
10 }

 

Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as as single unit. In encapsulation the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class, therefore it is also known as data hiding.

To achieve encapsulation in Java

  • Declare the variables of a class as private.

  • Provide public setter and getter methods to modify and view the variables values.

 

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

 

你可能感兴趣的:(Java inheritance, composition, encapsulation and polymophism)