Java Inheritance Update 2023 With Program And Example
nheritance is one of the essential concepts in object-orientated programming
(OOP) that lets in you to create a new magnificence this is based on an current elegance.
Inheritance allows you to define a brand new elegance (known as a subclass or derived magnificence) via inheriting
The homes and behaviors (fields and strategies) of an existing class (called a superclass or base magnificence).
This allows for code reuse and the introduction of a hierarchy of instructions.
Here's a simple Java program that demonstrates inheritance:
// Superclass (Base class)
class Animal {
String name;
Animal(String name) {
this.name = name;
}
void eat() {
System.out.println(name + " is eating.");
}
void sleep() {
System.out.println(name + " is sleeping.");
}
}
// Subclass (Derived class)
class Dog extends Animal {
Dog(String name) {
super(name); // Call the constructor of the superclass
}
void bark() {
System.out.println(name + " is barking.");
}
}
// Subclass (Derived class)
class Cat extends Animal {
Cat(String name) {
super(name); // Call the constructor of the superclass
}
void meow() {
System.out.println(name + " is meowing.");
}
}
public class InheritanceExample {
public static void main(String[] args) {
Dog dog = new Dog("Buddy");
Cat cat = new Cat("Whiskers");
dog.eat();
dog.sleep();
dog.bark();
cat.eat();
cat.sleep();
cat.meow();
}
}
In this program:
We define a Animal superclass with fields call and methods devour() and sleep().
We create subclasses, dog and Cat, which inherit from the Animal superclass.
Both canine and Cat training have their constructors, and they name the constructor of
The superclass using awesome(name) to initialize the call discipline.
Every subclass has extra strategies (bark() for canine and meow()
For Cat) further to the inherited techniques.
Within the essential approach, we create instances of dog and Cat and show how inheritance
Works by means of calling each inherited and subclass-unique methods.
That is a fundamental example of inheritance in Java, wherein subclasses inherit the houses
And behaviors of the superclass, taking into consideration code reuse and
Company of associated lessons in a hierarchy.