Curriculum
Inheritance is a core concept of object-oriented programming that allows a class to inherit properties and behaviors from another class. In Java, inheritance is implemented using the “extends” keyword. Here’s an example of how inheritance works in Java:
class Vehicle { int numWheels; int maxSpeed; void move() { // Method code here } } class Car extends Vehicle { int numDoors; void start() { // Method code here } }
In this example, the “Vehicle” class defines two instance variables, “numWheels” and “maxSpeed”, and a method called “move”. The “Car” class extends the “Vehicle” class using the “extends” keyword, which means that it inherits the instance variables and methods of the “Vehicle” class. It also defines a new instance variable, “numDoors”, and a new method called “start”.
There are different types of inheritance in Java, including:
Here’s an example of multilevel inheritance in Java:
class Animal { void eat() { // Method code here } } class Dog extends Animal { void bark() { // Method code here } } class GermanShepherd extends Dog { void protect() { // Method code here } }
In this example, the “Animal” class defines a method called “eat”. The “Dog” class extends the “Animal” class and defines a new method called “bark”. The “GermanShepherd” class extends the “Dog” class and defines a new method called “protect”. This means that the “GermanShepherd” class inherits the “eat” and “bark” methods from its parent classes.
Inheritance is a powerful feature of Java that allows you to reuse code and create hierarchies of classes that share properties and behaviors. It’s important to use inheritance carefully and to follow good object-oriented design principles to avoid creating complex and fragile class hierarchies.