Inheritance First Part
Inheritance First Part
Inheritance in Java
In Java, it is possible to inherit attributes and methods from one class to another. We group the
"inheritance concept" into two categories:
In the example below, the Car class (subclass) inherits the attributes and methods from
the Vehicle class (superclass):
Example
class Vehicle {
System.out.println("Tuut, tuut!");
}
class Car extends Vehicle {
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the value of the
modelName from the Car class
}
Did you notice the protected modifier in Vehicle?
We set the brand attribute in Vehicle to a protected access modifier. If it was set to private, the
Car class would not be able to access it.
Further details
Inheritance can be defined as the process where one class acquires the properties (methods and
fields) of another. With the use of inheritance the information is made manageable in a
hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child class)
and the class whose properties are inherited is known as superclass (base class, parent class).
extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax of
extends keyword.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Sample Code
Following is an example demonstrating Java inheritance. In this example, you can observe two
classes namely Calculation and My_Calculation.
Using extends keyword, the My_Calculation inherits the methods addition() and Subtraction() of
Calculation class.
Copy and paste the following program in a file with name My_Calculation.java
Example
class Calculation {
int z;
In the terminology of Java, a class which is inherited is called a parent or superclass, and the new
class is called child or subclass.
class Employee{
float salary=40000;
}
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
Ye video both part ko cover karey gi so half video is for this part and next half is for next part of
inheritance…..