Polymorphism

Download Report

Transcript Polymorphism

Polymorphism
and access control
What is polymorphism?
• In general: the ability of some concept to
take on different forms
• In Java: the ability to make identical
method calls invoke different behaviors
• This is one of the fundamental concepts in
Object-Oriented programming!
• Enables code reuse, encapsulation, etc.
RHS – SOC
2
What is polymorphism?
• We have already seen it – more or less
• Can be achieved either through interfaces
or inheritance (no fundamental difference)
• The principle is the same – a method is
defined in a fundamental class, and
several other classes can contain different
implementations of that method
RHS – SOC
3
What is polymorphism?
Animal
+ makeSound()
Duck
Mouse
+ makeSound()
+ makeSound()
RHS – SOC
4
What is polymorphism?
public class Duck extends Animal
{
public void makeSound() { print(”Quack”);}
}
public class Mouse extends Animal
{
public void makeSound() { print(”Squeak”);}
}
RHS – SOC
5
What is polymorphism?
public void makeAnimals()
{
ArrayList<Animal> zoo;
zoo = new ArrayList<Animal>();
zoo.add(new
zoo.add(new
zoo.add(new
zoo.add(new
zoo.add(new
Duck());
Mouse());
Mouse());
Duck());
Mouse());
makeNoise(zoo);
}
RHS – SOC
6
What is polymorphism?
public void makeNoise(ArrayList<Animal> zoo)
{
for (Animal a : zoo)
a.makeSound();
}
Output:
”Quack”
”Squeak”
”Squeak”
”Quack”
”Squeak”
RHS – SOC
7
What is polymorphism?
• A bit strange, when you think of it…
• The method makeNoise knows nothing at
all about the subclasses…
• …but still, the subclass-specific methods
are invoked!
• How is that possible?
RHS – SOC
8
What is polymorphism?
• ”In Java, method calls are
always determined by the
type of the actual object,
not the type of the object
reference”
• This is polymorphism
RHS – SOC
9
What is polymorphism?
• The method makeNoise will still work,
even if we add new subclasses! (”closed
for modification, open for extension”)
• It is the Java Virtual Machine (JVM), which
picks the correct method to call
• The JVM knows the true type of any object
• This principle is know as late binding
RHS – SOC
10
Choosing methods
• Multiple versions of the same method can
also be create through overloading
println(String output)
println(int output)
• However, method ”signatures” are different
• Compiler can pick correct method at
compile-time, this is early binding
RHS – SOC
11
Abstract classes
• An interface class only provides method
definitions, no implementation at all
• A super-class provides an implementation
for all its methods, which can be overwritten or used as-is
• Not the entire truth…
• We can choose only to provide an implementation for some of the methods
RHS – SOC
12
Abstract classes
public class DefaultShape
{
public void draw() { // do nothing }
public double getArea() { return 0.0;}
}
RHS – SOC
13
Abstract classes
public abstract class DefaultShape
{
public void draw() { // do nothing }
public abstract double getArea();
}
• This is known as an abstract class
• getArea is an abstract method
RHS – SOC
14
Abstract classes
• You can never create an
instance of an abstract
class (just like interface)
• You can have a variable of
this type
• You force the user to
provide an implementation
of the abstract methods
RHS – SOC
15
Abstract classes
• Is an abstract class just an interface?
• No, because they can have
– Instance fields
– Methods with implementation
– Constructors
• Why constructors…?
– Cannot be called by a user, but…
– …can be called from a sub-class
RHS – SOC
16
Preventing subclassing
• Maybe we do not want a user
to be able to create a subclass, or override a method
• Could be for security
reasons, etc.
• We can prevent this by
declaring a class or method
as being final
RHS – SOC
17
Preventing subclassing
public class SecureAccount extends BankAccount
{
...
public final boolean checkPassword(String pwd)
{
...
}
}
public final class String {...}
RHS – SOC
18
Access control
• Why could we not do this…?
// Overridden method in CheckingAccount
public void deposit(double amount)
{
balance = balance + amount;
private!
transactionCount++;
}
RHS – SOC
19
Access control
• Even a sub-class does not gain access to
private methods or instance fields
• Private really means private!
• Sub-classes must use get/set-methods,
just like any other user
• Not specifying public or private will provide
access at package level
RHS – SOC
20
Access control
public class Person
{
private String name;
public int height;
int weight;
}
//
//
//
//
Access
class only
everybody
all in package
• Unless a very good reason exists, stick to
public and private…
RHS – SOC
21
The Object class
• The system class Object
is a superclass of all
classes in Java!
• Polymorphism to the
extreme!?
• Which methods could be
meaningful to all Java
classes?
RHS – SOC
22
The Object class
• Not many…
• String toString() – returns a string
representation of the object
• boolean equals(Object other) –
tests if the object equals another object
• Object clone() – makes a full copy of
the object
RHS – SOC
23
The Object class
• String toString()
– Mostly used for debugging
– If not overwritten, outputs the class name plus
an object identifier
BankAccount@a122c09
– Usually overwritten to print out the values of
the instance fields, i.e. the state of the object
– Subclasses can print their own part
RHS – SOC
24
The Object class
• boolean equals(Object other)
– Often useful to know if two objects are ”equal”
– Equal by content, not by reference!
– We must first cast argument to correct class,
then check if instance fields are equal
– NOTE: For instance fields of non-primitive
types, we need to call their equals(...)
methods…
RHS – SOC
25
The Object class
• Object clone()
– Useful, if we want a real copy of an object, not
just a copy of the reference to the object
– Clone() method should return a new object,
with the same state as the given object
– Not trivial to clone an object, if the object
contains references to other objects
– Can make a shallow copy or deep copy
RHS – SOC
26
The Object class
Original
Deep
copy
Org.
Copy
Org.
Original
Copy
Copy
Copy
Shallow
copy
Org.
Org.
RHS – SOC
27
Exercises
• Self-check: 6, 15
• Review: R10.5
• Programming: P10.5, P10.6
RHS – SOC
28