Java Inheritance
Inheritance in Java is a mechanism where one class acquires the properties (fields) and behaviors (methods) of another class. It allows for hierarchical classification and promotes code reusability.
1. Types of Inheritance
- Single Inheritance: A class inherits from one superclass.
- Multilevel Inheritance: A class inherits from a subclass, forming a hierarchy.
Note: Java does not support multiple inheritance with classes (a class cannot inherit from more than one class).
2. Syntax
Use the extends
keyword to inherit from a class.
public class SuperClass {
// Superclass code
}
public class SubClass extends SuperClass {
// Subclass code
}
3. Example
public class Animal {
public void eat() {
System.out.println("Eating...");
}
}
public class Dog extends Animal {
public void bark() {
System.out.println("Barking...");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited from Animal class
dog.bark(); // Defined in Dog class
}
}
4. Method Overriding
Subclass can override methods of the superclass to provide specific implementation.
public class Animal {
public void makeSound() {
System.out.println("Some generic animal sound");
}
}
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow");
}
}
5. The super
Keyword
The super
keyword refers to the superclass and is used to access superclass methods and constructors.
6. Key Takeaways
- Inheritance promotes code reusability and hierarchical classification.
- Use the
extends
keyword to inherit from a superclass. - Method overriding allows subclasses to provide specific implementations.
- The
super
keyword accesses superclass members. - Understand the inheritance hierarchy to design effective class structures.