Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows a new class to inherit properties and behaviors (fields and methods) from an existing class. This promotes code reusability and establishes a natural hierarchy between classes.
Key Concepts
- Superclass (Parent Class): The class whose properties and methods are inherited.
- Subclass (Child Class): The class that inherits from the superclass.
extends
Keyword: Used to indicate that a class is inheriting from another class.- Method Overriding: A subclass can provide a specific implementation of a method that is already defined in its superclass.
super
Keyword: Used to refer to the superclass's methods and constructors.
Example
Let's consider a simple example to understand inheritance:
Superclass: Animal
public class Animal { // Fields protected String name; protected int age; // Constructor public Animal(String name, int age) { this.name = name; this.age = age; } // Method public void makeSound() { System.out.println("Some generic animal sound"); } }
Subclass: Dog
public class Dog extends Animal { // Additional field private String breed; // Constructor public Dog(String name, int age, String breed) { super(name, age); // Call the constructor of the superclass this.breed = breed; } // Overriding the makeSound method @Override public void makeSound() { System.out.println("Bark"); } // Additional method public void displayInfo() { System.out.println("Name: " + name + ", Age: " + age + ", Breed: " + breed); } }
Main Class to Test Inheritance
public class Main { public static void main(String[] args) { Dog dog = new Dog("Buddy", 3, "Golden Retriever"); dog.makeSound(); // Output: Bark dog.displayInfo(); // Output: Name: Buddy, Age: 3, Breed: Golden Retriever } }
Explanation
-
Superclass (Animal):
- Contains fields
name
andage
. - Has a constructor to initialize these fields.
- Defines a method
makeSound()
.
- Contains fields
-
Subclass (Dog):
- Inherits fields and methods from
Animal
. - Adds an additional field
breed
. - Uses the
super
keyword to call the constructor of the superclass. - Overrides the
makeSound()
method to provide a specific implementation. - Adds a new method
displayInfo()
to display the dog's information.
- Inherits fields and methods from
Practical Exercises
Exercise 1: Create a Subclass
Task: Create a subclass Cat
that inherits from Animal
. The Cat
class should have an additional field color
and override the makeSound()
method to print "Meow".
Solution:
public class Cat extends Animal { private String color; public Cat(String name, int age, String color) { super(name, age); this.color = color; } @Override public void makeSound() { System.out.println("Meow"); } public void displayInfo() { System.out.println("Name: " + name + ", Age: " + age + ", Color: " + color); } }
Exercise 2: Test the Subclass
Task: In the Main
class, create an instance of Cat
and call its methods.
Solution:
public class Main { public static void main(String[] args) { Cat cat = new Cat("Whiskers", 2, "Black"); cat.makeSound(); // Output: Meow cat.displayInfo(); // Output: Name: Whiskers, Age: 2, Color: Black } }
Common Mistakes
- Forgetting to Call the Superclass Constructor: Always use
super()
to call the superclass constructor if it has parameters. - Incorrect Method Overriding: Ensure the method signature in the subclass matches the superclass method exactly.
- Access Modifiers: Remember that private fields in the superclass are not directly accessible in the subclass. Use protected or public if you need direct access.
Summary
- Inheritance allows a class to inherit properties and methods from another class, promoting code reusability.
- The
extends
keyword is used to create a subclass. - Method overriding allows a subclass to provide a specific implementation of a method defined in its superclass.
- The
super
keyword is used to call the superclass's methods and constructors.
In the next topic, we will explore Polymorphism, which builds on the concept of inheritance to allow objects to be treated as instances of their superclass.
Java Programming Course
Module 1: Introduction to Java
- Introduction to Java
- Setting Up the Development Environment
- Basic Syntax and Structure
- Variables and Data Types
- Operators
Module 2: Control Flow
Module 3: Object-Oriented Programming
- Introduction to OOP
- Classes and Objects
- Methods
- Constructors
- Inheritance
- Polymorphism
- Encapsulation
- Abstraction
Module 4: Advanced Object-Oriented Programming
Module 5: Data Structures and Collections
Module 6: Exception Handling
Module 7: File I/O
Module 8: Multithreading and Concurrency
- Introduction to Multithreading
- Creating Threads
- Thread Lifecycle
- Synchronization
- Concurrency Utilities
Module 9: Networking
- Introduction to Networking
- Sockets
- ServerSocket
- DatagramSocket and DatagramPacket
- URL and HttpURLConnection