what is inheritance?
1.The new class that is created is known as subclass (child or derived class) and the existing class from where the child class is derived is known as superclass (parent or base class).
2.Inheritance in Java is a process of acquiring all the behaviours of a parent object.
1. Single Inheritance
In single inheritance, a single subclass extends from a single superclass. For example,
![Java Single Inheritance Class A inherits from class B.](https://cdn.programiz.com/sites/tutorial2program/files/java-single-inheritance.png)
The extends
keyword is used to perform inheritance in Java. For example,
class Animal {
// methods and fields
}
// use of extends keyword
// to perform inheritance
class Dog extends Animal {
// methods and fields of Animal
// methods and fields of Dog
}
practice program-1:
class aravind {
// field and method of the parent class
String name;
public void work() {
System.out.println("I am java developer");
}
}
// inherit from aravind
class pavithran extends aravind {
// new method in subclass
public void display() {
System.out.println("My name is " + name);
}
}
class Main {
public static void main(String[] args) {
// create an object of the subclass
pavithran details = new pavithran();
// access field of superclass
details.name = "suriya";
details.display();
// call method of superclass
// using object of subclass
details.work();
}
}
output:
My name is suriya
I am java developer
Method overriding
the same method is defined in both the superclass and the subclass, then the method of the subclass class overrides the method of the superclass. This is known as method overriding.
program-2: Method overriding in Java Inheritance
class aravind {
// field and method of the parent class
String name;
public void work() {
System.out.println("I am java developer");
}
}
// inherit from aravind
class pavithran extends aravind {
// overriding the work() method
public void work() {
System.out.println(" No,I am python developer");
}
// new method in subclass
public void display() {
System.out.println("My name is " + name);
}
}
class Main {
public static void main(String[] args) {
// create an object of the subclass
pavithran details = new pavithran();
// access field of superclass
details.name = "suriya";
details.display();
// call method of superclass
// using object of subclass
details.work();
}
}
output:
My name is suriya
No,I am python developer
(TBD)-The final Keyword link below
https://www.w3schools.com/java/java_inheritance.asp
Assignment task:
https://github.com/aravind2040/java-program/blob/master/Assignment2.java
Reference:
https://www.programiz.com/java-programming/inheritance
https://www.w3schools.com/java/java_inheritance.asp
Leave a comment