Java inheritance, composition, encapsulation and polymophism

Source: Internet
Author: User

composition meansHAS A
Inheritance meansIS A

Example: Car has a Engine and car is a Automobile

In programming the is represented as:

1 classEngine {}//The engine class.2 3 classautomobile{}//Automobile class which is the parent to Car class.4 5 //car is a Automobile, so Car class extends Automobile class.6 classCarextendsautomobile{7 8  //car has a engine so, car class have an instance of the engine class as its member.9  Privateengine engine;Ten}

encapsulation in Java are a mechanism of wrapping the data (variables) and code acting on the data (methods) Toget Her as as a single unit. In encapsulation the variables of a class would be hidden from other classes, and can is 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 getters methods to modify and view the variables values.

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

Java inheritance, composition, encapsulation and polymophism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.