child object behaving as a parent object.
by using Extends keyword we wil achive the inheritance
If we want to create a relationship between two or more classes, we use Inheritance in Java.
What is Inheritance?
Inheritance is a mechanism in Java where one class acquires the properties and behaviors (variables and methods) of another class.
Advantages of using inheritance:
- code reusability(less code duplication).
Example:
parent class:
package inheritance;
public class Employee {
int empId;
int salary;
public static void main(String[] args) {
}
public void work() {
System.out.println("Employee Work");
}
}
Child class:
package inheritance;
public class Developer extends Employee{
public static void main(String[] args) {
Developer dev1 = new Developer();
dev1.empId=101;
dev1.salary=10000;
System.out.println(dev1.empId);
System.out.println(dev1.salary);
dev1.work();
dev1.devwork();
}
public void devwork() {
System.out.println("Coding");
}
}
Top comments (0)