Inheritance
In object-oriented programming, inheritance is a mechanism that allows a class to inherit the properties and behaviors of another class. The class that inherits is called the subclass or derived class, and the class being inherited from is called the superclass or base class.
Inheritance is important in object-oriented programming because it enables code reuse and promotes the concept of hierarchy. With inheritance, a subclass can inherit and extend the attributes and methods of its superclass.
For example, let's consider a basic example with an Animal
superclass and a Dog
subclass. The Animal
class has a private name
attribute and a eat()
method. The Dog
class extends the Animal
class and adds a new method called bark()
.
1class Animal {
2 private String name;
3
4 public Animal(String name) {
5 this.name = name;
6 }
7
8 public void eat() {
9 System.out.println(name + " is eating.");
10 }
11}
12
13// Dog class inherits from the Animal class
14// Dog class is a subclass of Animal class
15// Animal class is the superclass of Dog class
16
17class Dog extends Animal {
18 public Dog(String name) {
19 super(name);
20 }
21
22 public void bark() {
23 System.out.println("Woof woof!");
24 }
25}
26
27public class Main {
28 public static void main(String[] args) {
29 Dog dog = new Dog("Buddy");
30 dog.eat();
31 dog.bark();
32 }
33}
In this example, the Dog
class inherits the name
attribute and eat()
method from the Animal
class. It also adds a new method bark()
. When we create an instance of the Dog
class, we can access and invoke both the inherited method eat()
and the subclass method bark()
.
Inheritance allows for the creation of more specialized classes based on existing classes, enabling code reuse, modularity, and ease of maintenance.
xxxxxxxxxx
class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + " is eating.");
}
}
class Dog extends Animal {
public Dog(String name) {
super(name);
}
public void bark() {
System.out.println("Woof woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Buddy");
dog.eat();
dog.bark();
}
}