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.

runtime polymorphism and compile time polymorphism

method overriding is good example of runtime polymorphism. Parent class has a version of method A() and subclasses override this method. At compile time it does figure out which method to call. only at Run time, JVM decides which method to call based on it infers whether it is

an object of parent class or subclass.

compile time polymorphism is just method overloading in Java. A method can take different variance of arguments.

 

转载于:https://www.cnblogs.com/touchdown/p/5174180.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值