Inheritance in Java
Imagine a Family: Explaining Inheritance in Java
Think of a parent and child. The child inherits some traits from the parent—like eye color, habits, or the ability to speak a certain language. Similarly, in Java, a class can inherit properties and behaviors (methods) from another class.
Let’s break it down:
Parent Class (Super Class): Think of it as a “general” class. For example, Animal.
Child Class (Sub Class): Think of it as a “specific” version of that class. For example, Dog or Cat.
If the Animal class has a method called makeSound(), the Dog and Cat classes can use that method too—they inherit it.
Simple Example:
class Animal {
void makeSound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
Now if we do this:
Dog myDog = new Dog();
myDog.makeSound(); // Inherited from Animal
myDog.bark(); // Defined in Dog
It works! The dog “inherited” the ability to make sound from the animal.
Inheritance allows one class (child) to reuse the properties and methods of another class (parent). It's like a child getting traits from a parent in real life.
Why is it useful?
Code Reusability: Write once, use in many places.
Cleaner Code: You avoid repeating the same code.
Flexibility: Easily extend or customize behavior.
Comments
Post a Comment