Java inheritance
Created By: chatGPT
In Java, inheritance is a fundamental concept of object-oriented programming that allows one class to inherit properties and behaviors (methods) from another class. This helps in promoting code reusability and establishes a relationship between classes. The class that inherits is called the subclass (or child class), while the class from which properties are inherited is called the superclass (or parent class).
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
In the example above, we have an Animal class with a method
eat()
. The Dog class inherits from the Animal class using the extends
keyword. This means that the Dog class has access to the eat()
method in addition to its own method bark()
.public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Calls the method from the Animal class
dog.bark(); // Calls the method from the Dog class
}
}
When you run the Main
class, it will output:
- This animal eats food.
- The dog barks.
This demonstrates method inheritance, where the subclass can use methods defined in the superclass.
Java also supports multilevel inheritance, where a class can inherit from another class that is already a subclass. For example, if we create a Puppy class that extends the Dog class, the Puppy class will inherit methods from both Dog and Animal.
class Puppy extends Dog {
void weep() {
System.out.println("The puppy weeps.");
}
}
In this case, the Puppy class can access the
bark()
method from the Dog class and the eat()
method from the Animal class, in addition to its own weep()
method. Here’s how the Main class would look like with the Puppy class:public class Main {
public static void main(String[] args) {
Puppy puppy = new Puppy();
puppy.eat(); // From Animal class
puppy.bark(); // From Dog class
puppy.weep(); // From Puppy class
}
}
The output will be:
- This animal eats food.
- The dog barks.
- The puppy weeps.
This illustrates how inheritance allows for a hierarchical relationship where subclasses can inherit behaviors and properties from their superclasses.