Better Living in Objectville

Better Living in Objectville
Adriano Cruz [email protected]
Departamento de Ciˆ
encia da Computa¸c˜
ao
Instituto de Matem´
atica
UFRJ
April 2, 2015
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
1 / 67
Section Summary
1
Inheritance
2
Members
3
Polymorphism
4
Exercise
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
2 / 67
Starting
What have all four classes in common?
Square
+rotate()
+playSound()
Adriano Cruz (DCC-IM-UFRJ)
Circle
+rotate()
+playSound()
Triangle
+rotate()
+playSount()
07 - Inheritance and Polymorphism
Amoeba
+rotate()
+playSound()
April 2, 2015
3 / 67
Super Class
Common features
Shape
+rotate()
+playSound()
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
4 / 67
Super Class and Sub Classes
Shape is a superclass.
Others a subclasses.
All Together
Shape
+rotate()
+playSound()
Square
Adriano Cruz (DCC-IM-UFRJ)
Circle
Triangle
07 - Inheritance and Polymorphism
Amoeba
April 2, 2015
5 / 67
Amoebas are different!
Amoeba class override the rotate() and playSound()
methods. Overriding means that a subclass redefines one of its
inherited methods.
All Together
Shape
+rotate()
+playSound()
Square
Circle
Triangle
Amoeba
+rotate()
+playSound()
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
6 / 67
An Example
Doctors
Superclass
Doctor
One instance variable
One method
+worksAtHospital: boolean
+treatPatient(): void
Surgeon
FamilyDoctor
+treatPatient(): void
+makeIncision(): void
Overrides the inherited
treatPatient() method
Adds one new method
Adriano Cruz (DCC-IM-UFRJ)
Subclasses
+makesHouseCalls: boolean
+giveAdvice(): void
Adds one new
instance variable
Adds one new method
07 - Inheritance and Polymorphism
April 2, 2015
7 / 67
Implementing the example
p u b l i c c l a s s Doctor {
boolean worksAtHospital;
v o i d t r e a t P a t i e n t () {
// perform a checkup
}
}
p u b l i c c l a s s F a m i l y D o c t o r e x t e n d s Doctor {
boolean makesHouseCalls;
v o i d giveAdvice () {
// give Advice
}
}
p u b l i c c l a s s Surgeon e x t e n d s Doctor {
v o i d t r e a t P a t i e n t () {
// perform surgery
}
v o i d m a k e I n c i s i o n () {
// uhh
}
}
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
8 / 67
Questions?
Doctor
+worksAtHospital: boolean
+treatPatient(): void
Surgeon
+treatPatient(): void
+makeIncision(): void
FamilyDoctor
+makesHouseCalls: boolean
+giveAdvice(): void
1
How many instance variables does Surgeon have?
2
How many instance variables does FamilyDoctor have?
3
How many methods does Doctor have?
4
How many methods does Surgeon have?
5
How many methods does FamilyDoctor have?
6
Can a FamilyDoctor do treatPatient()?
7
Can a FamilyDoctor do makeIncision()?
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
9 / 67
New problem
Design a simulation program that lets the user simulate a
group of animals in an environment.
We have a list of animals to be simulated, but not all.
Animals will move around, doing whatever it is that each
particular type is programmed to do.
We need to allow programmers to add new kinds of animals.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
10 / 67
Steps
Step 1: Look for objects that have common attributes and
behaviours.
Step 2: What do these six objects have in common?
Step 3: How are these objects related?
Step 4: Define the inheritance tree?
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
11 / 67
Instance Variables
picture – the file name representing the .jpeg of the animal.
food – the type of food the animal eats.
hunger – an int representing the hunger level of the animal.
boundaries – values representing the height and width of the space the
animal will roam around in.
location – coordinates where the animal is.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
12 / 67
Methods
makeNoise() – noise the animal makes.
eat() – behaviour for when the animal finds his preferred food.
sleep() – behaviour for when the animal is considered asleep.
roam() – behaviour for when the animal is not sleeping or eating.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
13 / 67
Diagram
Animal
+picture
+food
+hunger
+boundaries
+location
+makeNoise()
+eat()
+sleep()
+roam()
Lion
Hippo
Adriano Cruz (DCC-IM-UFRJ)
Tiger
Dog
07 - Inheritance and Polymorphism
Cat
Wolf
April 2, 2015
14 / 67
Are they all equal?
Do all animals eat the same way?
Which methods should we override?
Does a dog and a lion make the same noise?
Do they eat the same things?
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
15 / 67
Modified Diagram
Animal
+picture
+food
+hunger
+boundaries
+location
+makeNoise()
+eat()
+sleep()
+roam()
Wolf
+makeNoise()
+eat()
Lion
+makeNoise()
+eat()
Hippo
+makeNoise()
+eat()
Adriano Cruz (DCC-IM-UFRJ)
Tiger
+makeNoise()
+eat()
Dog
+makeNoise()
+eat()
07 - Inheritance and Polymorphism
Cat
+makeNoise()
+eat()
April 2, 2015
16 / 67
More opportunities for abstraction
Wolf and dog?
Lion, tiger and cat?
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
17 / 67
Modified once again
Animal
+picture
+food
+hunger
+boundaries
+location
+makeNoise()
+eat()
+sleep()
+roam()
Feline
+roam()
Canine
+roam()
Hippo
Tiger
+makeNoise()
+eat()
+makeNoise()
+eat()
Cat
Wolf
Lion
+makeNoise()
+eat()
Adriano Cruz (DCC-IM-UFRJ)
Dog
+makeNoise()
+eat()
+makeNoise()
+eat()
07 - Inheritance and Polymorphism
+makeNoise()
+eat()
April 2, 2015
18 / 67
Which method?
Animal
Wolf w = new Wolf();
w.makeNoise();
w.roam();
+picture
+food
+hunger
+boundaries
+location
+makeNoise()
+eat()
+sleep()
+roam()
w.eat();
w.sleep();
Canine
+roam()
The lowest one wins!
When calling a method
the most specific
version of the method is
used.
The JVM starts walking
up the inheritance tree
at the invoked class.
Wolf
+makeNoise()
+eat()
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
19 / 67
Sharpen your Pencil
Find relationships that make sense. Not everything can be connected to
something else.
Class
Musician
Rock Star
Fan
Bass Player
Concert Pianist
Superclasses
Adriano Cruz (DCC-IM-UFRJ)
Subclasses
07 - Inheritance and Polymorphism
April 2, 2015
20 / 67
IS-A and HAS-A
When one class inherits from another, the subclass extends the
superclass.
Triangle IS-A Shape.
Cat IS-A Feline.
Surgeon IS-A Doctor.
Bathroom IS-A Tube or Bathroom HAS-A Tube?
If X extends Y, X IS-A Y .
The relationship IS-A works in only one direction.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
21 / 67
IS-A and HAS-A
The IS-A test works anywhere in the inheritance tree.
Canine extends Animal.
Wolf extends Canine.
Wolf extends Animal.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
22 / 67
Some Words
A class that is derived from another class is called a subclass (also a
derived class, extended class, or child class).
The class from which the subclass is derived is called a superclass
(also a base class or a parent class).
Excepting Object, which has no superclass, every class has one and
only one direct superclass (single inheritance).
In the absence of any other explicit superclass, every class is implicitly
a subclass of Object.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
23 / 67
Be Warned!
Constructors are not members
A subclass inherits all the members (fields, methods, and nested classes)
from its superclass. Constructors are not members, so they are not
inherited by subclasses, but the constructor of the superclass can be
invoked from the subclass.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
24 / 67
Dumb Questions!
Q: What if the superclass wants to use the subclass
version of the method?
A: It is not possible. A superclass will not necessarily know
about any of its subclasses.
Q: What if I want to use both the superclass and my
overriding version of the a method?
A: It is possible.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
25 / 67
Using superclass method
p u b l i c v o i d roam () {
s u p e r . roam () ; // the i n h e r i t e d v e r s i o n
// now my roam stuff .
}
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
26 / 67
What to do?
DO: use inheritance when one class is a more specific type of a
superclass.
DO: consider using inheritance when you have behaviour that
sould be shared among multiple classes of the same type.
DO NOT: use inheritance just so that you can reuse code from another
class.
DO NOT: use inheritance if the subclass and superclass do not pass the
IS-A test.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
27 / 67
Section Summary
1
Inheritance
2
Members
3
Polymorphism
4
Exercise
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
28 / 67
Members?
Methods and instance (nonlocal) variables are collectively known as
members.
You can modify a member with both access and nonaccess modifiers.
Usually methods and variable members are given access control in
exactly the same way.
Members can use four access control levels:
default
public
protected
private
A class can use just two:
default
public
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
29 / 67
Members: Who gets what?
What does it mean for code in one class to have access to a member
of another class?
Can a method in one class have access a member of another class?
This means to use the dot (.) operator.
Can a subclass inherit a member of its superclass?
Which, if any, members of a superclass can be accessed through
inheritance?
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
30 / 67
Members: Who gets what?
A subclass inherits members of the superclass.
Members include instance variables and methods.
A superclass can choose whether or not it wants a subclass to inherit
a particular member by the level of access the particular member is
given.
From the most restrictive to the least:
private
default
protected
public
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
31 / 67
public members
A public member means that all other classes, regardless of the
package they belong to, can access the member (assuming the class
itself is visible).
pac kage book ; // different packages
i m p o r t abrave .*;
c l a s s Too {
p u b l i c s t a t i c v o i d main ( String [] args ) {
Blob o = new Blob () ;
// accessible , public class Blob and method testIt
o . testeIt () ;
}
}
pac kage cert ; // different packages
p u b l i c c l a s s Blob {
p u b l i c v o i d testIt () {
System . out . println ( " blob " ) ;
}
}
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
32 / 67
public members
If the member of the superclass is declared public the subclass
inherits that member regardless of whether both classes are in the
same package.
pac kage cert ;
p u b l i c c l a s s Roo {
p u b l i c String doRooThings () {
r e t u r n " fun " ;
}
}
pac kage notcert ;
i m p o r t cert . Roo ;
c l a s s Cloo e x t e n d s Roo {
p u b l i c v o i d testCloo () {
System . out . println ( doRooThings () ) ;
}
}
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
33 / 67
public members
The doRooThings() method is invoked without having to preface it
with a reference.
The Roo class declares the doRooThings() member as public.
A subclass of Roo can call its own inherited doRooThings() method.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
34 / 67
private members
private members can not be accessed by code in any class other than
the class in which the private member was declared.
pac kage cert ;
p u b l i c c l a s s Roo {
p r i v a t e String doRooThings () {
r e t u r n " fun " ;
}
}
pac kage notcert ;
i m p o r t cert . Roo ;
c l a s s UseARoo {
p u b l i c v o i d testIt () {
Roo r = new Roo () ; // OK Roo is public
// Compiler error
// doRoothings is private
System . out . println ( r . doRooThings () ) ;
}
}
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
35 / 67
private members and Inheritance
What about a subclass that tries to inherit a private member of its
class?
It is not possible!
pac kage cert ;
p u b l i c c l a s s Roo {
p r i v a t e String doRooThings () {
r e t u r n " fun " ;
}
}
pac kage cert ; // same package
c l a s s Cloo e x t e n d s Roo {
p u b l i c v o i d testCloo () {
// compiler error
System . out . println ( doRooThings () ) ;
}
}
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
36 / 67
Protected and Default Members
Protected and default access control levels are almost identical.
A protected member can be accessed (through inheritance) by a
subclass even if the subclass is in a different package.
A default member (think package level) may be accessed only if the
class accessing the member belongs to the same package.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
37 / 67
Default Members
Illegal access different packages.
pac kage certification ;
p u b l i c c l a s s OtherClass {
v o i d testIt () { // default access
System . out . println ( " OtherClass " ) ;
}
}
pac kage somethingelse ;
i m p o r t certification . OtherClass ;
c l a s s AccessClass {
s t a t i c p u b l i c v o i d main ( Strint [] args ) {
OtherClass o = new OtherClass () ;
o . testIt () ;
}
}
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
38 / 67
Protected Members
Legal access through inheritance.
pac kage certification ;
p u b l i c c l a s s Parent {
p r o t e c t e d i n t x = 9;
}
}
pac kage other ; // other package
i m p o r t certification . Parent ;
c l a s s Child e x t e n d s Parent {
p u b l i c v o i d testIt () {
// x is inherited
System . out . println ( " x is " + x ) ; // no problem
}
}
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
39 / 67
Determining Access
Visibility
From the same class
From any class
in the same package
From a subclass
in the same package
From a subclass
outside the same package
From any non-subclass
class outside package
Adriano Cruz (DCC-IM-UFRJ)
Public
Yes
Yes
Protected
Yes
Yes
Default
Yes
Yes
Private
Yes
No
Yes
Yes
Yes
No
Yes
Yes, through
inheritance
No
No
No
No
No
Yes
07 - Inheritance and Polymorphism
April 2, 2015
40 / 67
Access Modifiers
There are three access modifiers: public, protected, private.
However there are four access levels!!??
The fourth access level (default) is what you get when you don’t use
any of the three modifiers.
Every class, method and instance variable you declare has an
access control, whether you declare or not.
A class can be declared with only public or default access, the other
two does not make sense for a class.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
41 / 67
Packages
Java is a package-centric language.
A package is a namespace that organizes a set of related classes and
interfaces.
Conceptually you can think of packages as being similar to different
folders on your computer.
It is assumed that you put all your classes into packages.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
42 / 67
Public Access
A class declaration with the public keyword give all classes from all
packages access to the public class.
Do not forget that if a public class is in a differente package from the
class you are writing, you will still need to import the public class.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
43 / 67
Example
pac kage cert ;
c l a s s Beverage ;
pac kage exam . stuff ;
i m p o r t cert . Beverage ;
c l a s s Tea e x t e n d s ←֓
Beverage {}
Tea will not compile because its superclass Beverage is in a
different package and has default acess.
pac kage cert ;
p u b l i c c l a s s Beverage ; // OK now !!
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
44 / 67
Dumb Questions!
Q: So what does inheritance give you?
A:
Get rid of duplicate code.
When it is necessary to modify the code, there is only
one place to update.
Define a common protocol (methods etc) for a group of
classes.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
45 / 67
Section Summary
1
Inheritance
2
Members
3
Polymorphism
4
Exercise
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
46 / 67
Creating an Object
1
2
3
4
5
6
7
8
9
0
myDog
Dog object
Step 2: new Dog();
Dog
Step 1: Dog myDog
Step 3: Dog myDog = new Dog();
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
47 / 67
Polymorphism
In the example the reference type (myDog) and the object are the same.
With polymorphism they can be different.
Animal myDog = new Dog()
The reference type can be a superclass of the actual object type.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
48 / 67
Modified once again
Animal
+picture
+food
+hunger
+boundaries
+location
+makeNoise()
+eat()
+sleep()
+roam()
Feline
+roam()
Canine
+roam()
Hippo
Tiger
+makeNoise()
+eat()
+makeNoise()
+eat()
Cat
Wolf
Lion
+makeNoise()
+eat()
Adriano Cruz (DCC-IM-UFRJ)
Dog
+makeNoise()
+eat()
+makeNoise()
+eat()
07 - Inheritance and Polymorphism
+makeNoise()
+eat()
April 2, 2015
49 / 67
Example I.a
p u b l i c c l a s s Animal {
p u b l i c v o i d makeNoise () {
System . out . println ( " Animal ! " );
}
p u b l i c v o i d eat () {
System . out . println ( " Animal eating . " ) ;
}
p u b l i c v o i d sleep () {
System . out . println ( " Animal sleeping " ) ;
}
p u b l i c v o i d roam () {
System . out . println ( " Animal roaming . " ) ;
}
}
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
50 / 67
Example I.b
p u b l i c c l a s s Canine e x t e n d s Animal {
p u b l i c v o i d roam () {
System . out . println ( " I am a Canine roaming . " ) ;
}
}
p u b l i c c l a s s Dog e x t e n d s Canine {
p u b l i c v o i d makeNoise () {
System . out . println ( " I am a Dog making noise . " ) ;
}
p u b l i c v o i d eat () {
System . out . println ( " I am a Dog eating . " ) ;
}
}
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
51 / 67
Example I.c
p u b l i c c l a s s TestAnimal {
p u b l i c s t a t i c v o i d main ( String [] args ) {
Animal [] animals = new Animal [5];
animals [0]
animals [1]
animals [2]
animals [3]
animals [4]
=
=
=
=
=
new
new
new
new
new
Dog () ;
Cat () ;
Wolf () ;
Hippo () ;
Lion () ;
f o r ( Animal t : animals ) {
System . out . println ( " Doing stuff " ) ;
t . makeNoise () ;
t . eat () ;
t . sleep () ;
t . roam () ;
System . out . println () ;
}
}
}
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
52 / 67
Example results
Doing stuff
I am a Dog making noise.
I am a Dog eating.
Animal sleeping
I am a Canine roaming.
Doing stuff
I am a Cat making noise!
I am a Cat eating.
Animal sleeping
I am a Feline roaming.
Doing stuff
I am a Wolf making noise.
I am a Wolf eating.
Animal sleeping
I am a Canine roaming.
Doing stuff
I am a Hippo making noise.
I am a Hippo eating.
Animal sleeping
Animal roaming.
Doing stuff
I am a Lion making noise!
I am a Lion eating.
Animal sleeping
I am a Feline roaming.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
53 / 67
Polymorphic Arguments and Return Types
It is possible to have polymorphic arguments and return types.
It is possible to declare a reference variable of a supertype and assign
a subclass object to it.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
54 / 67
Example II
p u b l i c c l a s s Vet {
p u b l i c v o i d giveShot ( Animal a ) {
System . out . println ( " Giving shot . " ) ;
a . makeNoise () ;
}
}
p u b l i c c l a s s PetOwner {
p u b l i c v o i d start () {
Vet v = new Vet () ;
Dog d = new Dog () ;
Hippo h = new Hippo () ;
v . giveShot ( d ) ;
v . giveShot ( h ) ;
}
}
p u b l i c c l a s s TestPetOwner {
p u b l i c s t a t i c v o i d main ( String [] args ) {
PetOwner p = new PetOwner () ;
p . start () ;
}
}
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
55 / 67
Advantages
With polymorphism it is possible to write code that does not have to
change when new subclasses are introduced.
A Vet can treat animals that
extends the class Animal.
Adriano Cruz (DCC-IM-UFRJ)
A Giraffe extending the class
Animal!
07 - Inheritance and Polymorphism
April 2, 2015
56 / 67
Dumb Questions!
Q: If I do not have access to the source code of a class,
can I use subclass to do that? To extend the class and
override the method with my own better code?
A: Yes. That is another advantage of OO.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
57 / 67
Dumb Questions!
Q: Can you extend any class? Or is it like class members
where if the class is private you can’t inherit it?
A: There is no private class, except in a special case called inner
class, which we will discuss later. There are three things that
can prevent a class from being subclassed.
1 The first is access control. A class can be made
non-public when it is not declared as public. A
non-public class can be subclassed only by classes in the
same package (later).
2 When the keyword modifier final is used. A final class
means it is the end of the inheritance line.
3 If a class has only private constructors (later) it can not
be subclassed.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
58 / 67
Dumb Questions!
Q: Why would we want a final class?
A:
Typically we do not want.
However when it is necessary to guarantee that the
methods will work the way they were designed.
The Java API class has many final classes. For instance
the String class.
Q: Can you make a method final, without making the
whole class final?
A: Yes, mark the method with the final modifier. The method is
protected.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
59 / 67
Keeping the contract
Rules for overriding!
The methods are the contract!
Arguments must be the same, and
return types must be compatible.
The method can not be less accessible.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
60 / 67
Keeping the contract
Appliance
Appliance
+turnOn(): boolean
+turnOff(): boolean
+turnOn(): boolean
+turnOff(): boolean
Toaster
Toaster
+turnOn(level:int): boolean
-turnOn(): boolean
This is not an override.
It is a legal overload!
Adriano Cruz (DCC-IM-UFRJ)
It is not legal.
The access was restricted.
Indicated by the - signal (private)
07 - Inheritance and Polymorphism
April 2, 2015
61 / 67
Overloading
Overloaded methods MUST change the argument list.
Method overloading is nothing more than having two methods with the
same name but different argument lists.
It is possible to write multiple versions of a method with different
arguments lists.
Overloaded methods CAN change the return type.
The return types can be different, as long as the arguments are
different.
It is not possible to change only the return type.
Overloaded methods CAN change the access modifier.
It is possible to change the access levels in any direction.
Overloaded methods CAN declare new or broader checked exceptions.
later.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
62 / 67
Overloading
It is possible to overload a method in a subclass. The subclass
inherits the method and overloads it.
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
63 / 67
Overload Example
c l a s s Multiplier {
p u b l i c i n t multiply ( i n t x, i n t y) {
ret u rn x * y;
}
p u b l i c d o u b l e m u l t i p l y( d o u b l e x , d o u b l e y ) {
ret u rn x * y;
}
}
p u b l i c c l a s s testMultiplier {
p u b l i c s t a t i c v o i d main ( String [] args ) {
M u l t i p l i e r a = new M u l t i p l i e r () ;
i n t r e s u l t I n t = a . m u l t i p l y (2 , 3) ;
d o u b l e r e s u l t D o u b l e = a . m u l t i p l y (2.0 , 3.0) ;
}
}
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
64 / 67
Section Summary
1
Inheritance
2
Members
3
Polymorphism
4
Exercise
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
65 / 67
Mixed Messages
What is the output of the program?
class A {
i n t ivar = 7;
v o i d m1 () {
System . out . println ( " A ' s m1 , " );
}
v o i d m2 () {
System . out . println ( " A ' s m2 , " );
}
v o i d m3 () {
System . out . println ( " A ' s m3 , ") ;
}
}
c l a s s B extends A {
v o i d m1 () {
System . out . println ( " B ' s m1 , " );
}
}
c l a s s C extends B {
v o i d m3 () {
System . out . println ( "C ' s m3 , " +(←֓
ivar +6) ) ;
}
}
1
p u b l i c c l a s s Mixed2 {
p u b l i c s t a t i c v o i d main ( String [ ] ←֓
args ) {
A a new A () ;
B b new B () ;
C c new C () ;
A a2 = new C () ;
/* Incluir os candidatos aqui */
}
}
(a)
(b)
(c)
(d)
b . m1 () ;
c . m2 () ;
a . m3 () ;
c . m1 () ;
c . m2 () ;
c . m3 () ;
a. m1 () ;
b. m2 () ;
c. m3 () ;
a2 . m1 () ;
a2 . m2 () ;
a2 . m3 () ;
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
66 / 67
.
The End
Adriano Cruz (DCC-IM-UFRJ)
07 - Inheritance and Polymorphism
April 2, 2015
67 / 67