In object-oriented programming (OOP), Inheritanceallows reusing of software by extending an existing class members. When creating a new class, you may want the new class to inherit the properties and members of an existing class instead of implementing same proprieties and members again in the new class. Here, the existing class is called the superclass, and the new class is called the subclass.

For example, a Circleis a Shape. Thus, in Java, class Circlecan be said to inherit from class Shape. In this context, class Shapeis a superclass and class Circleis a subclass. Some inheritance examples (superclass:subclasses):

Student: GraduateStudent, UndergraduateStudent

Shape: Circle, Triangle, Rectangle, Sphere, Cube

Bank Account: Checking Account, Savings Account

Vehicle: Car, Truck, Boat, Bicycle

To demonstrate inheritance in action, first let us create a Vehicle class

1

2

3

4

5

6

7

classVehicle{

protectedStringlicensePlate=null;

publicvoidsetLicensePlate(Stringlicense){

this.licensePlate=license;

}

}

In Java inheritance is declared using the extendskeyword. We now extend the Vehicle class to have Car class:

1

2

3

4

5

6

7

classCarextendsVehicle{

protectedintnumberOfSeats=0;

publicintgetNumberOfSeats(){

returnthis.numberOfSeats;

}

}

The protected Keyword

In addition to access modifiers public and private, protectedaccess offers an intermediate level of access between them. Remember that a superclass’sprivatemembers are not accessible for other classes, including its subclasses. However, the protectedmembers of a superclass are accessible from its subclasses. Yet, it is different from public members, which can be accessed by any class, regardless of inheritance relationship. The public and protected members are similar in the fact that their original access modifiers are retained in the subclasses – public members of the superclass become public members of the subclass, and protected members of the superclass become protected members of the subclass.

Overriding Method and the super Keyword

In a subclass, Java allows the code to override (redefine) methods defined in the superclass. Using the superkeyword a subclass can access the methods in its superclass. Here is an example of using the superkeyword in a constructor and a method.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

classCarextendsVehicle{

publicCar(inti_NumberOfSeats){

super();

//perform other initialization here

numberOfSeats=i_NumberOfSeats;

}

publicvoidsetLicensePlate(Stringlicense){

super.setLicensePlate(license);

}

publicStringtoString(){

return"The car has "+numberOfSeats+" seats. Its license is "+licensePlate;

}

}

The SportsCar class can be created by extending Car class

1

2

3

4

5

6

7

8

9

10

classSportsCarextendsCar{

doublemaxSpeed=0;

publicSportsCar(inti_NumberOfSeats,doubled_MaxSpeed){

super(i_NumberOfSeats);

//perform other initialization here

maxSpeed=d_MaxSpeed;

}

}

When you override a method in a subclass, it is recommended to use @Override annotation. This way, if you misspell a method name or not correctly matching the parameters, you will be warned that your method does not actually override the intended methods as you think it does. Secondly, it makes your code easier to understand because it is more obvious about which methods are overwritten.

1

2

3

4

5

6

7

8

9

10

11

12

13

&nbsp;&nbsp;&nbsp;

classSportsCarextendsCar{

@Override

publicvoidsetLicensePlate(Stringlicense){

this.licensePlate=license.toLowerCase();

}

@Override

publicStringtoString(){

returnsupper.toString()+". Its max speed is "+maxSpeed;

}

}

The final Keyword

The finalkeyword has different semantic depending on the context:

A finalclass cannot be inherited. It is useful when there is a good reason to prohibit inheritance. Technically speaking, a developer marks a class as finalto indicate that he has not considered or do not expect the class to be inherited.

A finalmethod cannot be overriden. The design does not expect the method to be changed even in its subclasses.

A finalvariable can only be initialized once, making it safe to ensure the value cannot be changed once assigned.

A complete example

To complete this article, we will test how the objects of Car class and SportsCar class different in behavior.

Vehicle Class : Superclass

1

2

3

4

5

6

7

classVehicle{

protectedStringlicensePlate=null;

publicvoidsetLicensePlate(Stringlicense){

this.licensePlate=license;

}

}

Car Class extending Vehicle

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

classCarextendsVehicle{

protectedintnumberOfSeats=0;

publicCar(inti_NumberOfSeats){

super();

//perform other initialization here

numberOfSeats=i_NumberOfSeats;

}

publicvoidsetLicensePlate(Stringlicense){

super.setLicensePlate(license);

}

publicStringtoString(){

return"The car has "+numberOfSeats+" seats. Its license is "+licensePlate;

}

publicintgetNumberOfSeats(){

returnthis.numberOfSeats;

}

}

SportsCar Class extending Car Class

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

classSportsCarextendsCar{

doublemaxSpeed=0;

publicSportsCar(inti_NumberOfSeats,doubled_MaxSpeed){

super(i_NumberOfSeats);

//perform other initialization here

maxSpeed=d_MaxSpeed;

}

@Override

publicvoidsetLicensePlate(Stringlicense){

this.licensePlate=license.toLowerCase();

}

@Override

publicStringtoString(){

returnsuper.toString()+". Its max speed is "+maxSpeed;

}

}

Main Test Method

1

2

3

4

5

6

7

8

9

10

11

12

13

//This class tests the above classes

publicclassVehiclesTest

{

publicstaticvoidmain(Stringargs[])

{

Car personalCar=newCar(4);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

personalCar.setLicensePlate("PERSONAL-BN123");

System.out.println(personalCar);

SportsCar sportsTeam=newSportsCar(2,200);

sportsTeam.setLicensePlate("SPORTS-AB989");

System.out.println(sportsTeam);

}

}

Notice that the SportsCarhas its license lowercased and itstoString() method append the Car‘s toString() with its own max speed.

The above code produce:

The car has 4 seats. Its license is PERSONAL-BN123The car has 2 seats. Its license is sports-ab989. Its max speed is 200.0

Summary

Inheritancereduces development time through reusing of existing code base in a hierarchical manner.

A superclassprotected members have an intermediate level of protection between publicand privateaccess. They can be accessed by its subclasses.

Java allows overridingmethods of the superclass. We can use the superkeyword to access the superclass methods.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Cookie settingsACCEPT

Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are as essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are as essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.

Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.