As one of the OOP principles, inheritance is designed to centralize the common functionality of many different objects. As a result of that, it reduces duplicated code in many classes.
Inheritance introduces two types of classes: “superclass” and “subclass.” The subclass inherits from the superclass. The superclass is the same thing as the “base class.” The subclass contains not only all the methods and the fields inherited from the superclass, but also other methods and fields defined by the subclass.
For example, we define a new class called Sedan that inherits from the Car class we created earlier. The Car class implements an interface called Auto. In the Sedan class, we define a Boolean field isFourDoorHatchback and a method called isFourWheelDrive() .
This example tells us that we can create an object from a superclass (i.e., Car) instantiated from its subclass (i.e., Sedan). All the methods and fields under its superclass are available as expected, but the methods and fields under its subclass are not accessible.
This clearly tells us that we are not allowed to create a subclass object (i.e., Sedan) instantiated from its superclass (i.e., Car).
In Java, however, it doesn’t support multiple inheritance. Instead, it uses an interface to achieve the same goal as what multiple inheritance attempts to do in other programming languages.
Problems
- 1.Which of the following is the correct syntax to indicate that class A is a subclass of B?
- (a)
public class A : super B {
- (b)
public class B extends A {
- (c)
public class A extends B {
- (d)
public A(super B) {
- (e)
public A implements B {
- (a)
- 2.Consider the following classes:public class Vehicle {...}public class Car extends Vehicle {...}public class SUV extends Car {...}Which of the following are legal statements?
- (a)
Car c = new Vehicle();
- (b)
SUV s = new SUV();
- (c)
SUV s = new Car();
- (d)
Car c = new SUV();
- (e)
Vehicle v = new Car();
- (f)
Vehicle v = new SUV();
- (a)