Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Inheritance & Polymorphism in OOP: Time Saving with Twix & Reese's, Study notes of Object Oriented Programming

Learn about inheritance and polymorphism in object-oriented programming through the example of creating classes for Twix and Reese's candies. Discover how to save time and energy by reusing code and defining methods that do different things with different objects.

Typology: Study notes

2021/2022

Uploaded on 09/27/2022

hawking
hawking 🇬🇧

4.3

(24)

268 documents

1 / 7

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Inheritance and Polymorphism
The concept of inheritance is a common feature of an object-oriented programming
language. Inheritance allows a programmer to define a general class, and then later
define more specific classes that share or inherit all of the properties of the more general
class. This allows the programmer to save time and energy that might otherwise be spent
writing duplicate code.
Related to inheritance is the concept of polymorphism. Polymorphism allows us to define
different methods with the same name, but have those methods do different things with
different objects. This is related to method overloading, but as we will see is different in
that the position of the object in the inheritance hierarchy determines what method gets
invoked.
For example, perhaps we would like to build an application about candy. For starters,
let’s say we want to do something with Twix bars and something with Reese’s Peanut
Butter Cups. We might make classes like the following:
Public Class Twix
Private calories As Integer
Private ingredients As ArrayList
Public Sub New()
calories = 580
ingredients = New ArrayList
ingredients.Add("Sugar")
ingredients.Add("Chocolate")
ingredients.Add("Caramel")
End Sub
Public Function GetInfo() As String
Dim sIngred As String
Dim i As Integer
sIngred = CStr(ingredients(0))
For i = 1 To ingredients.Count - 1
sIngred = sIngred & " " & CStr(ingredients(i))
Next
Return "Calories: " & CStr(calories) & _
" Ingredients: " & sIngred
End Function
End Class
Public Class Reeses
Private calories As Integer
Private ingredients As ArrayList
Public Sub New()
calories = 460
ingredients = New ArrayList
ingredients.Add("Sugar")
ingredients.Add("Chocolate")
ingredients.Add("Peanut Butter")
End Sub
pf3
pf4
pf5

Partial preview of the text

Download Inheritance & Polymorphism in OOP: Time Saving with Twix & Reese's and more Study notes Object Oriented Programming in PDF only on Docsity!

Inheritance and Polymorphism

The concept of inheritance is a common feature of an object-oriented programming

language. Inheritance allows a programmer to define a general class, and then later

define more specific classes that share or inherit all of the properties of the more general

class. This allows the programmer to save time and energy that might otherwise be spent

writing duplicate code.

Related to inheritance is the concept of polymorphism. Polymorphism allows us to define

different methods with the same name, but have those methods do different things with

different objects. This is related to method overloading, but as we will see is different in

that the position of the object in the inheritance hierarchy determines what method gets

invoked.

For example, perhaps we would like to build an application about candy. For starters,

let’s say we want to do something with Twix bars and something with Reese’s Peanut

Butter Cups. We might make classes like the following:

Public Class Twix Private calories As Integer Private ingredients As ArrayList

Public Sub New() calories = 580 ingredients = New ArrayList ingredients.Add("Sugar") ingredients.Add("Chocolate") ingredients.Add("Caramel") End Sub

Public Function GetInfo() As String Dim sIngred As String Dim i As Integer

sIngred = CStr(ingredients(0)) For i = 1 To ingredients.Count - 1 sIngred = sIngred & " " & CStr(ingredients(i)) Next Return "Calories: " & CStr(calories) & _ " Ingredients: " & sIngred End Function End Class Public Class Reeses Private calories As Integer Private ingredients As ArrayList

Public Sub New() calories = 460 ingredients = New ArrayList ingredients.Add("Sugar") ingredients.Add("Chocolate") ingredients.Add("Peanut Butter") End Sub

Public Function GetInfo() As String Dim sIngred As String Dim i As Integer

sIngred = CStr(ingredients(0)) For i = 1 To ingredients.Count - 1 sIngred = sIngred & " " & CStr(ingredients(i)) Next Return "Calories: " & CStr(calories) & _ " Ingredients: " & sIngred End Function End Class

You should already be familiar with how one might use these classes. For example, the

following code creates two candy bars and prints their info:

Dim twixbar As New Twix Dim reesescups As New Reeses Console.WriteLine(twixbar.GetInfo) Console.WriteLine(reesescups.GetInfo)

This program outputs:

Calories: 580 Ingredients: Sugar Chocolate Caramel Calories: 460 Ingredients: Sugar Chocolate Peanut Butter

This might be fine for some applications, but right off the bat we can see that we are

duplicating a lot of the same code. For example, the GetInfo() subroutine is going to be

the same for any candy bar. As the program is now, if we had 100 different candy bars,

we would have 100 different GetInfo() subroutines.

Instead, we can take advantage of a natural ordering of candy bars. We can visualize the

types of candy bars in a hierarchy as follows:

In this example, we define the calories and ingredients variables in the CandyBar class

since these are variables that apply to any Candy Bar. These variables are inherited by all

classes below it, so they automatically get access to the variables without having to

redefine them.

At the CandyBar level we also have a function, GetInfo(). It returns a string of the

calories and ingredients. It is also accessible by any class defined below it, so the

function only exists in one place.

When we create an object, the constructors for all the parent classes will also be invoked.

Consequently, when we make a Twix object, VB.NET will first invoke the constructor

for CandyBar, then the constructor for ChocolateBar, and finally Twix would be last.

Here is our sample code:

CandyBar

calories

ingredients

New() : Has sugar

GetInfo()

ChocolateBar

New() : Has choc

Twix

New() : Has cara

Cal = 580

Reeses

New() : Has PB

Cals = 460

Public Class CandyBar Protected calories As Integer Protected ingredients As ArrayList

Public Sub New() ingredients = New ArrayList ingredients.Add("Sugar") ' All candy bars have sugar End Sub

Public Function GetInfo() As String Dim sIngred As String Dim i As Integer

sIngred = CStr(ingredients(0)) For i = 1 To ingredients.Count - 1 sIngred = sIngred & " " & CStr(ingredients(i)) Next Return "Calories: " & CStr(calories) & _ " Ingredients: " & sIngred End Function End Class

Public Class ChocolateBar Inherits CandyBar

Public Sub New() ingredients.Add("Chocolate") ' All chocolate bars have choc End Sub End Class

Public Class Twix Inherits ChocolateBar

Public Sub New() calories = 580 ingredients.Add("Caramel") End Sub End Class

Public Class Reeses Inherits ChocolateBar

Public Sub New() calories = 460 ingredients.Add("Peanut Butter") End Sub End Class

Here is code that we can run, whose output is identical to before:

Dim twixbar As New Twix Dim reesescups As New Reeses Console.WriteLine(twixbar.GetInfo) Console.WriteLine(reesescups.GetInfo)

In CandyBar Class:

Overridable Function GetInfo() As String Dim sIngred As String Dim i As Integer

sIngred = CStr(ingredients(0)) For i = 1 To ingredients.Count - 1 sIngred = sIngred & " " & CStr(ingredients(i)) Next Return "Calories: " & CStr(calories) & _ " Ingredients: " & sIngred End Function

Now we can define a function of the same name in the Twix class except we use the

keyword overrides. The MyBase.GetInfo() call invokes the parent definition of GetInfo:

In Twix Class:

Overrides Function GetInfo() As String Return MyBase.GetInfo() & ". Two for me, none for you" End Function

Now if we run our code:

Dim twixbar As New Twix Dim reesescups As New Reeses Console.WriteLine(twixbar.GetInfo) Console.WriteLine(reesescups.GetInfo)

We get:

Calories: 580 Ingredients: Sugar Chocolate Caramel Two for me, none for you Calories: 460 Ingredients: Sugar Chocolate Peanut Butter

This feature can be very useful for customizing subroutines at more specific levels of the

inheritance hierarchy while retaining the generality offered at higher levels of abstraction.

It turns out that every class we make is actually a descendant of the predefined class

named Object. This means that every class we create will inherit methods from Object.

This is how the ArrayList is able to handle an array of any data type – it is defined to hold

the type Object which is a superclass of all other classes.

It turns out that VB.NET defines a function for the Object class. This function is then

inherited automatically by every class we make. The function is getType() which will

return back the type of the class.

There are many other subtleties regarding the hierarchy of objects (e.g. we can assign a

variable to be of type Twix to a variable defined of type CandyBar, but not vice versa)

that we will skip here but you would cover in more detail in a class on Object Oriented

Programming.