CET203 SOFTWARE DEVELOPMENT Session 2B Constructors, Overriding and Overloading

Preview:

Citation preview

CET203SOFTWARE DEVELOPMENT

Session 2BConstructors, Overriding and

Overloading

Objectives

• Understand how constructors are used within an inheritance hierarchy

• Use overloaded constructors and methods• Know when and how to use overriding• Understand the position of the Object class within an

inheritance hierarchy and override the ToString method within subclasses

Constructors

• A constructor for a superclass should deal with general initialization.

• Each subclass can have its own constructor for specialised initialization.

• How do we inherit constructor behaviour?• In the earlier examples we have seen (probably

without even noticing!) that when a subclass object is created both its constructor and that of its superclass are executed.

Exercise 1

ConstructorTestA.sln

Exercise 1

class MyClass{ public MyClass() { Console.WriteLine("MyClass constructed"); }}

class MySubClass : MyClass{ public MySubClass() { Console.WriteLine("MySubClass constructed"); }}

Consider the classes:

What will be the result of the following?

MySubClass myObj = new MySubClass();

Constructors with parameters

• If your superclass has a parameterized constructor then you need to ensure your subclasses provide the superclass with what it needs

• If the superclass constructor requires parameters then you must include a constructor for each derived class

• The subclass constructor must at least provide values for each parameter in the superclass

• These parameters are passed “up” to the superclass constructor using the keyword base

• The subclass may also contain additional parameters for use in its own constructor

Using baseclass MySubClass : MySuperClass{ public MySubClass (parameters) : base (super-parameters) {

// local initialization }}

Exercise 2

• Consider a class Employee with the following constructor:Public Employee (String name, int salary){ this.name = name; this.salary = salary;}

• PartTimeEmployee is a subclass of Employee which contains an additional integer instance variable numHours

• What would be a suitable constructor for PartTimeEmployee which would set name, salary and numHours to initial values entered via parameters?

Overloading Constructors

• We have already seen that we can have multiple constructors in the same class

• We may have a constructor with no parameters where the values are initialised to some default values

• Or we may have a constructor which takes parameters and uses their values to perform the initialisation

• We can have any number of constructors, so long as they each have a different “method signature” i.e a different set of parameters

• This is called overloading• It is not just the case for constructors, any method can be

overloaded

Constructor Examples/Rules

MySuperClass()

MySuperClass

MySubClass

MySuperClass()MySuperClass(x)

MySuperClass

MySubClass()can call baseconstructor

MySubClass

MySuperClass(x)

MySuperClass

MySubClass()must call base

constructor

MySubClass

Demonstration

ConstructorTestB.sln

Publication Case Study

Book

author

OrderCopies()

Magazine

orderQtycurrIssue

AdjustQty()RecvNewIssue()

Publication

titlepricecopies

SellCopy()

Exercise 3

PublicationsA.sln

Exercise 3

• Suggest constructors for the Publication and Book classes which set initial values for the instance variables from appropriate parameters.

Overriding methods• A subclass inherits the methods of its superclass.• A subclass always provides at least that set of methods, and often

more.• However, the implementation of a method can be changed in a

subclass.• This is overriding the method.• If we are going to allow a method of the superclass to be

overridden then we need to mark it as virtual• We write a new version of the method in the subclass which

replaces the inherited one.• We indicate that the method has been overridden using the

override keyword• Properties can also be overridden if different functionality is

required in their get/set methods

DiscMag

• A special category of magazine which has a disc attached to each copy.

• These must be checked when a new issue arrives, so we want some additional functionality in the RecvNewIssue() method to remind us to do this.

• Achieve this by overriding RecvNewIssue() in the DiscMag subclass.

• If we wish to implement the new functionality in addition to existing functionality then the overridden method must also call the superclass version:base.RecvNewIssue();

New RecvNewIssue()Magazine

orderQtycurrIssue

AdjustQty()RecvNewIssue()

DiscMag

RecvNewIssue()

• The definition of RecvNewIssue() in DiscMag overrides the inherited one.

• Magazine is not affected – it retains its original definition of RecvNewIssue()

• Note that the method appears in both classes on the class diagram

Exercise 4

PublicationsB.sln

Exercise 4

• The definition of the Magazine class is shown on the following slide

• Write the code for the class DiscMag, a subclass of Magazine which overrides the RecvNewIssue method

• The DiscMag version of RecvNewIssue should output the message "Check discs attached to this magazine“ in addition to the existing functionality

• Are any changes necessary to the Magazine class?

Magazine classclass Magazine : Publication{ private int orderQty; // property omitted private String currIssue; // property omitted public Magazine(String title, double price, int copies, int orderQty, String currIssue) : base(title, price, copies) { this.orderQty = orderQty; this.currIssue = currIssue; } public void AdjustQty(int qty) { orderQty = qty; } public void RecvNewIssue(String newIssue) { Copies = orderQty; currIssue = newIssue; }}

‘Operations’

• Formally, ‘RecvNewIssue()’ is an operation.• This (one) operation is implemented by two different

methods, one in Magazine and the overriding one in DiscMag.

• Up to now we have never distinguished between operations and methods because they have effectively been the same thing.

• Most people don’t worry too much about this distinction except when it becomes significant.

• It is an important part of ‘polymorphism’ which we will meet in a later session.

The ‘Object’ class

• In C# all objects are (direct or indirect) subclasses of a class called Object.

• If a class is not declared to extend another then it implicitly extends Object.

• Object defines no instance variables but several methods.

• Generally these methods will be overridden by new classes to make them useful.

• An example is the ToString() method.

Object superclass

Book

author

OrderCopies()

Magazine

orderQtycurrIssue

AdjustQty()RecvNewIssue()

Publication

titlepricecopies

SellCopy()

Object

ToString()

Not normally shown on diagrams

The ToString method

• ToString() has the signaturepublic String ToString()

• The version of ToString() defined by Object produces output like:

"Publication.Book“• To be generally useful we need to override this to

give a more meaningful string.• When overriding ToString() remember to use the

override keyword

Overriding ToString()In Publicationpublic override String ToString(){ return title;}

In Bookpublic override String ToString(){ return base.ToString() + " by " + author;}

In Magazinepublic override String ToString(){ return base.ToString() + " (" + currIssue + ")";}

Demonstration

PublicationsC.sln

Recommended