Java Lesson 9: Inheritance, Polymorphism & Subclasses

Advertisements

Hello everybody,

It’s Michael, and today’s Java lesson will be on inheritance, polymorphism & subclasses.

First of all, what is inheritance? In Java, it’s possible for one class to inherit the attributes and methods of another class. Using the keyword extends, any class can inherit methods and attributes from another class. The class that is inheriting the methods and attributes is called the subclass or child class while the class that is providing the methods for the subclass is called the parent class or superclass.

Polymorphism is related to inheritance, but the two aren’t interchangeable. Inheritance lets us use methods and attributes from another class by means of the extends keyword while polymorphism lets us use those inherited methods to perform a single action in different ways.

Let’s say we have a superclass called Sport which has a single method-score. Subclasses of Sport could include Bowling, AmericanFootball, Golf, Basketball, etc. and each subclass would have their own implementation of a scoring system* (for instance, baseball would use runs, golf would use par, etc.)

  • *this is where polymorphism would come in

Here’s some code we can use to approach the problem in the above example (keep in mind I didn’t run any of this on NetBeans; I’m just using this solely as an example):

Let’s start with some code for the main class:

public class Sport

{

public void score ()

{

System.out.print(“Score system: “);

}

}

 

 

And here’s the code for two subclasses-AmericanFootball and Baseball:

class AmericanFootball extends Sport

{

public void score ()

{

System.out.print(“Score system: Points”)

}

}

 

class Baseball extends Sport

{

public void score ()

{

System.out.print (“Score system: Runs”);

}

}

As you can see, there is no main method for the main class Sport but rather the void method score, which is used in my two subclasses-AmericanFootball and Baseball. One thing you will notice is that-and this is where polymorphism comes into play-the score method produces a different output for each class. For instance, if you were to create an object of the main class-Sport-and call the score method, you would get the output Score system: . If you were to create an object of class AmericanFootball and call the score method, you would get the output Score system: Points. If you did the same thing for the Baseball class, you would get the output Score System: Runs.

My point is that with polymorphism, you can use the same method across various classes and tailor the method to each class.

Thanks for reading,

Michael

Leave a ReplyCancel reply