码迷,mamicode.com
首页 > 编程语言 > 详细

Java inheritance, composition, encapsulation and polymophism

时间:2016-02-01 02:06:35      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/touchdown/p/5174180.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!