Introduction to Java
What is Inheritance in Java?
In Java, you can create a subclass from a parent class by inheriting the parent class state (attributes) and behavior (methods). Unless a class is declared as final, you can inherit from any class in Java. For instance, if there is a parent class called vehicle, you can create a class called car by inheriting the vehicle class. Not all vehicles are cars, but all cars are a type of vehicle.
Let's dive into this concept further with a code example below.
Declaring Inheritance in Java
To find the answer to that question, let's create a car class that inherits the above-class vehicle in the same file after the vehicle class.
Output: I'm accelerating
Program Explanation: In the above code, we declare a class called the car and use the extends keyword to inherit it with the vehicle class. So when an object of this car class is created, it inherits the accelerate method of the parent class vehicle, as evident from the output.
So in this example, the superclass is the vehicle class, whereas the subclass is the car class.
Next, you'll discover how the attributes are inherited in the subclass.
Let's put this line of code in the model declaration for the vehicle class:
Then at the end of the main method of the Car class, let's output the model of the car:
If you compile and run the whole program, you'll get the output: I'm accelerating The model of the car is: Sedan
However, there are better practices than the above method of directly accessing a class variable, as you must keep the variables private and only access them via methods. It's suitable for security purposes. But since the subclass is inheriting, we can use the protected modifier when declaring variables in the superclass.
Using Methods and Variables of the Superclass
Often there are situations where you"ll have to define variables in the subclass, which has different values than the variables in the superclass. In such scenarios, if you want to access the superclass variables, you must use the
super keyword. Let's consider the code below. In this code, we have created a separate class to include the main method.
Which of the following modifiers can you use to declare variables in the superclass if you want them to be accessed by the subclass?
Select a few correct answers
When you wish to access the variables or methods of the parent class, which keyword do you use?
Select the correct answer