Inheritance in Java

aimtocode

Inheritance :

It allows the extension and reuse of existing code without having to rewrite the code from scratch. Inheritance involves the creation of new classes(derived classes) from the existing ones(base classes), thus enabling the creation of a hierarchy of classes that simulate the class and Subclass concept of the real world. The new derived class inherits the members of the base class and also adds its own.

When a Class extends another class it inherits all non-private members including fields and methods. Inheritance in Java can be best understood in terms of Parent and Child relationship, also known as Super class(Parent) and Sub class(child) in Java language.

aimtocode

The whole idea behind encapsulation is to hide the implementation details from users. If a data member is private it means it can only be accessed within the same class. No outside class can access private data member (variable) of other class.

Encapsulation can be achieved by: Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables.


Syntax :



Output :

 Programmer salary is:40000.0
 Bonus of Programmer is:1000 

Example 2:



Output :

 aimtocode
 Teacher
 Java
 Teaching
aimtocode