0% found this document useful (0 votes)
4 views

Lecture4 Overloading

The document discusses object-oriented concepts like overloading, overriding, and polymorphism. It provides examples of overloading methods and overriding methods in subclasses. Polymorphism allows calling the proper subclass method through a parent class reference.

Uploaded by

Luffy Luffy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lecture4 Overloading

The document discusses object-oriented concepts like overloading, overriding, and polymorphism. It provides examples of overloading methods and overriding methods in subclasses. Polymorphism allows calling the proper subclass method through a parent class reference.

Uploaded by

Luffy Luffy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Object Oriented Design and Analysis

CPE 372

Lecture 4

Overloading, Overriding and Polymorphism

Dr. Sally E. Goldin


Department of Computer Engineering
King Mongkut’s University of Technology Thonburi
Last update: 1 Feb 2020
Bangkok, Thailand
Inheritance and Class Hierarchies

Class Student represents a


single university student at
KMUTT.

Registration system will


create one instance for
each registered student.

2
Create Subclasses to Specialize

Class GradStudent has some


additional members and
methods.

However, it also inherits the


members and methods of its
parent class.

So we can call calculateGpa()


on a GradStudent instance.

3
Class Hierarchy


Does an ExchangeStudent have an advisor?

Can I call hasPassedToefl() method on a PhDStudent?

Is GradStudent a subclass of PhDStudent?

What if I want to create a class for high school students?

Depend what want 4


kind you to represent
More Terminology
The parent class is sometimes called the base class
www
The child class is called the derived class
www

General OO terminology – not Java-specific


5
Exercise 3 Solution
AbstractShape class has three subclasses

Triangle: defined by 3 points

Square: defined by 1 point plus side length

Diamond: defined by 1 point plus vertical and


horizontal axes

6
AbstractShape Class

Almost all data items are stored in


the superclass

counter, allFigures, colors are


static members

I was able to implement move(),


draw() and drawAll() as concrete
methods in the superclass, rather
than as abstract methods

Perimeter and area methods must


be abstract because the formula
depends on the type of shape
c none me me
7
Exercise 3 Class Hierarchy

Bold italic methods


are abstract methods
her
inbounds
abstact shape

8
OO Design Rule of Thumb: 3

Maximize the amount of data and behavior


that you implement in the superclass

9
Let’s add new behavior

What if we want to sometimes not only draw the outline of the


shape but also fill it with some color?

We could add a new method


drawFilled(Graphic2D graphics, Color fillColor)
That method could call draw(), then add extra code for doing the fill
process
However, a more “object-oriented” way to do this is to have a second
version of draw() that has an extra argument.

draw
Draw
10
draw fill color
To Use This Method...

Triangle myshape = new Triangle(12,10,32,11,20,22);


myshape.draw(graphics, Color.magenta);

Where would we define this new version of draw()?


www

11
1 Overloading
This is an example of overloading a method.
“Overloading” means creating multiple versions of a
method that have the same function name, but different
arguments and/or a different return value.
(We can also say the different implementations have different
signatures.)

ex Point c int n int y


Point cdouble x double
y

ring 12
overload
Another Example owr I
Original constructor for Triangle: Orrison mis
b public Triangle(int x1, int y1, int x2, int y2, int x3, int y3);
y
Or you might implement it like this:
his
public Triangle(Point p1, Point p2, Point p3);
gaffe
It’s possible to do both!
triangle
You could also have a default constructor:
public Triangle()
r{ to help
Triangle(100,0,100,100,150,200);
}

13
What are the advantages of overloading?

Focus attention on behavior rather than implementation


aGannon5 078
Provide greater convenience for different calling code
Only create overloaded methods when all variants do
basically the same thing!

14
I new discussion
Adding a New Subclass

What if we want to create and draw circles?

(xc, yc)

radius

Defined by center point coordinates plus radius.


Let’s add the constructor, perimeter calculator and area
calculator and see if it works.

15
What went wrong???

16
Draw Method in AbstractShape
Circle doesn't have
any point

Starts at the anchor point (point 0)

Iterates through all the points in the vertices ArrayList

Draws lines from current point to the next point

Uses modulus so last line will close the shape

But Circle does not store any points!

rehnauhidnmonmnqamognidwoonnwioiiduno.eu
owns
in'rudowwonrurtuny 17
The Solution
Implement specialized version of draw() in the Circle class
public void draw(Graphics2D graphics)
{
graphics.setPaint(drawColor);
/* drawOval takes center plus width and height */
graphics.drawOval(anchor.x,anchor.y,2*radius,2*radius);
/* label it near the anchor point */
onion int labelx = anchor.x + 5;
int labely = anchor.y - 5;
oigo graphics.drawString(new String(" " + shapeId),labelx,labely);
no'rniiu's
}

Creating a method in a subclass that has the same name and


signature as one in the superclass is called overriding the method.

18
Smart find what to call
Java will call the right method!
The program will start at the level of the subclass and search
upwards in the class hierarchy until it finds a matching method
(matching name and signature)

Can select itself which


to
class use
ClassC cObj= new ClassC();
ClassB bObj= new ClassB();

useclassA cObj.foo(200,200);
UseclassC cObj.foo(new Point(230,80));
useclassBbObj.foo(200,200);
useclass A bObj.foo(new Point(230,80));
19
Overriding allows you to escape from strict
inheritance

Get the benefits of subclassing

Provides customization if necessary
iimwni Venu

Overriding can either replace or expand behavior
Circle draw() replaces AbstractShape.draw()
3DSquare draw() might expand on it

20
voodoo

If necessary, can invoke a specific version

Call the superclass method:


public void callParentFoo()
{
super.foo(12,23);
}
noclass9Wsuper class
Call the local method:
public void callLocalFoo()
{
Point p = new Point(12,23);
this.foo(p);
}

98class voomfiOS 21
A fromMhs
Polymorphism many shape
many shape
Consider the method drawAll() in AbstractShape
/**
* Static method to draw all the shapes
* that have been created so far.
* @param graphics Graphics context for drawing.
*/
public static void drawAll(Graphics2D graphics)
{
for (int i=0; i < allFigures.size(); i++)
{
AbstractShape shape = allFigures.get(i);
shape.draw(graphics);
}
}

If we have instances of Circle in our list, we will be calling different methods


depending on which concrete subclass of AbstractShape is stored in the
shape variable. drawAll() doesn’t know and doesn’t care.
22
drawAll hai
“Polymorphism” comes from Greek meaning “many forms”.
The most common use of polymorphism in OOD occurs when a
nation's
parent class reference is used to refer to a child class object and to
call child class methods that override the parent method.

23
Another Example

In this example, every call to calcArea() invokes a


different child method.

/**
* Static method to print the area of all the shape
* that have been created so far.
* @param graphics Graphics context for drawing.
*/
public static void showAreas()
{
for (int i=0; i < allFigures.size(); i++)
{
AbstractShape shape = allFigures.get(i);
double area = shape.calcArea();
System.out.println(“The area of shape “ + shapeId +
“ is “ + area);
}
}

24
Another Example: PolyDemo

Every class in Java is a subclass of Object


Object provides a standard method toString()
Some classes override that method

Contents of objectlist

String Integer Double Date JPanel Square ...

IntegerC227

von Bu class Iof


25
What if we want to know
irrinody
the actual class?
canfind out
Java has the ability to “introspect” -
u
momclasses
to allow us to examine and
methods while the program is
running
D The getClass() method returns the
runtime class of an object (as an
Object!)
D We can use toString() to print the
name of the class

class
26
All talk about method
Summary of Terms

Overloading
To create multiple methods in one class which have the
same method name but different signatures
(arguments)

27
Summary of Terms (2)

Overriding
To create a method in a subclass that has the same
name and signature as a method in its superclass, but
a different implementation which is specific to that
subclass Inooooow mon ironnon's now

28
Summary of Terms (3)

Polymorphism
A situation in which multiple
subclasses of a superclass have
methods with the same names and
signatures, but different
implementations. noworms
When the polymorphic method is
called on an object identified as the
superclass, the correct subclass
method is automatically invoked.

29

You might also like