Inheritance
Tuesday, December 5, 2023
Inheritance in Java is one of the fundamental pillars of Object-Oriented Programming (OOP). It provides a mechanism through which a class can inherit properties and behaviors from another class.
Class Hierarchy
In inheritance, classes are organized in a hierarchy, where a more specific class (subclass or child class) inherits characteristics from a more general class (superclass or parent class). For example, if you have a class "Animal" as a superclass, you could have subclasses like "Dog" and "Cat."
Inheritance models the "is-a" relationship. If a class B inherits from a class A, it can be said that B is a type of A. A Dog is a type of Animal.
In Java, inheritance is implemented using the extends
keyword. When you define a child class, you use extends
to indicate from which class it is inheriting.
public class Dog extends Animal {
// code of the Dog class
}
The subclass inherits both methods and attributes from the superclass. This means it can use and, in some cases, modify the behavior defined in the superclass.
public class Animal {
public void eat() {
System.out.println("The animal eats.");
}
}
public class Dog extends Animal {
// The Dog class inherits the eat method from the Animal class
}
Inherited members (methods and attributes) can be used directly in the subclass. Visibility depends on access modifiers (public, private, protected).
public class Dog extends Animal {
public void bark() {
System.out.println("Woof, woof!");
}
public void performActivity() {
eat(); // Access to the inherited method from the superclass
bark(); // Subclass's own method
}
}
Share it
Share it on your social media and challenge your friends to solve programming problems. Together, we can learn and grow.
Copied
The code has been successfully copied to the clipboard.