Java Software Solutions Foundations of Program Design

Download Report

Transcript Java Software Solutions Foundations of Program Design

Slide #1
Inheritance
•
•
Inheritance is a fundamental object-oriented technique
that supports reuse of software.
In this lecture:
• Inheritance
• Polymorphism, widening & narrowing
• Method overriding
• protected and final modifiers
• A word about multiple inheritance
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #2
Inheritance
•
•
•
•
•
Inheritance allows us to derive a new class from an
existing one
The existing class is called the superclass or baseclass.
derived class is called the subclass or derived-class.
Instances of the derived class inherit all the properties
and functionality that is defined in the base class.
Usually, the derived class adds more functionality and
properties.
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #3
Example
Clock
AlarmClock
setAlarm()
setAlarmState()
The Interdisciplinary Center, Herzelia
setTime()
getSeconds()
getMinutes()
getHours()
secondElapsed()
...
AnalogClock
getSecondsPointerAngle()
getMinutesPointerAngle()
getHoursPointerAngle()
Lecture 8, Introduction to CS - Information Technologies
Slide #4
The is a relationship
•
•
•
•
Inheritance creates an is-a relationship. AnalogClock
is a Clock, AlarmClock is a Clock.
Everything that can be done with a Clock object can
also be done with an AlarmClock object.
An AnalogClock is a special kind of Clock. It has all
the functionality of a clock and some more.
The subclass instances are more specific than the
instances of the superclass.
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #5
Example
Turtle
IntelligentTurtle
The Interdisciplinary Center, Herzelia
moveForwards(float size)
turnLeft(float teta)
turnRight(float teta)
tailUp()
...
drawPolygon(int n, float size)
drawSquare(int n)
Lecture 8, Introduction to CS - Information Technologies
Slide #6
The extends Keyword
/**
* A logo turtle that knows how to draw composite
* figures such as polygons.
*/
public class IntelligentTurtle extends Turtle {
/**
* Draws a perfect polygon.
* @param n The number of edges
* @param edgeSize The size of each edge
*/
public void drawPolygon(int n, float edgeSize) {
float teta = 360.0f / n;
for (int i=0; i<n; i++) {
moveForwards(edgeSize);
turnLeft(teta);
}
}
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #7
Example
// Draws a perfect polygon whose number of edges is
// given by the user and the size of is edge is fixed
class PerfectPolygon {
static final float EDGE_SIZE = 100.0f;
/**
* Draws a perfect polygon.
*/
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
IntelligentTurtle painter =
new IntelligentTurtle();
painter.tailDown();
painter.drawPolygon(n, EDGE_SIZE);
}
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #8
When to derive a subclass?
•
•
•
Derived class should normally extend the functionality
of the superclass
In certain cases, a derived class would change some of
the functionality of the superclass
Thumb Rule: Subclass only when it is reasonable
from the point of view of the abstractions!
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #9
Examples
Point
Pixel
Employee
Frame
Manager
Dialog
TextField
PasswordField
FileDialog
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #10
What is Inherited?
•
When you derive a class from a given base class:
• The subclass inherits all the fields of the base class
• It inherits all the methods of the base class
•
•
You have to declare the constructors of the subclass
from scratch
Private fields and methods are inherited but cannot be
accessed directly from the code of the subclass
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #11
Switch Example
Switch




Switch()
boolean isOn()
setOn(boolean)
isOn
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #12
Switch Code
/**
* An electronic switch that can be on/off.
*/
public class Switch {
// Records the state of the switch
private boolean isOn;
/**
* Checks if this switch is on.
* @return true if the switch is on.
*/
public boolean isOn() {
return isOn;
}
/**
* Sets the state of the switch on/off.
*/
public void setOn(boolean state) {
isOn = state;
}
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #13
Switch vs. Adjustable Switch
on
off
an adjustable switch has
a “level of current” dial
pressing the adjustable switch
turns it on
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #14
Inheriting AdjustableSwitch from Switch

Switch



AdjustableSwitch


The Interdisciplinary Center, Herzelia
Switch()
isOn()
setOn(boolean)
AdjustableSwitch()
setLevel(float)
getLevel()
Lecture 8, Introduction to CS - Information Technologies
Slide #15
AdjustableSwitch Code
/**
* An adjustable electronic switch.
*/
public class AdjustableSwitch extends Switch {
// The level of current (0-100)
private float level;
// . . . getLevel() and setLevel()
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #16
AdjustableSwitch Code (cont.)
/**
* Sets the level of current
* @param level the required level of current(0%-100%)
*/
public void setLevel(float level) {
if (level < 0.0f || level > 100.0f) {
throw new IllegalArgumentException();
}
this.level = level;
}
/**
* Returns the level of current of the switch.
*/
public float getLevel() {
return level;
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #17
AdjustableSwitch Example
AdjustableSwitch


isOn





setOn(boolean)
isOn()
AdjustableSwitch()
setLevel(float)
getLevel()
level
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #18
Private Fields - Inherited but not Accessible
•
•
•
Notice that an AdjustableSwitch object has a
state variable isOn
This variable is inherited from Switch
However, it cannot be accessed directly from the
code of AdjustableSwitch because it is defined
as private in Switch - i.e., it is encapsulated
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #19
Inheritance: a Basis for Code Reusability
•
•
•
•
•
Fast implementation - we need not write the implementation
of AdjustableSwitch from scratch, we just implement the
additional functionality.
Ease of use - If someone is already familiar with the base class,
then the derived class will be easy to understand.
Less debugging - debugging is restricted to the additional
functionality.
Ease of maintenance - if we need to correct/improve the
implementation of Switch, AdjustableSwitch is
automatically corrected as well.
Compactness - our code is more compact and is easier to
understand.
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #20
Example: Changing the Base Class
•
•
•
Suppose that we want to add the property of ‘maximal
power’ to our representation of a switch.
This property is suitable in adjustable switches as
well (the inheritance supports our abstraction!).
Inheritance allows us to add this property only in the
base class. The changes will automatically take place
in the inherited class.
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #21
Changing the Switch Class
/**
* An electronic switch that can be on/off.
*/
public class Switch {
// Records the state of the switch
private boolean isOn;
// The maximal power of this switch
private float maxPower;
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #22
Changing the Switch Class
/**
* Constructs a new switch.
* @param power the maximal power of the switch.
*/
public Switch(float maxPower) {
if (maxPower <= 0.0f) {
throw new IllegalArgumentException();
}
this.maxPower = maxPower;
}
/**
* Returns the maximal power of this switch.
*/
public float getMaxPower() {
return maxPower;
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #23
Constructors Must Be Redefined!
•
•
•
Note that the constructor of Switch receives a
parameter - maxPower - and initializes the private
field with the same name.
We have to define a constructor for
AdjustableSwitch that receives the same
parameter and initializes this field. But this field is
private, so there is no direct access to it.
In general, when we invoke a constructor of a
subclass, we first have to construct the superclass
“part” of the subclass. We do this by using the super
keyword.
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #24
AdjustableSwitch - Redefinition of Constructor
/**
* Constructs an adjustable switch.
* @param power the maximal power of the switch.
* @exception IllegalArgumentException if the power
* is negative.
*/
public AdjustableSwitch(float power) {
super(power);
}

The first line of the constructor calls the constructor of the
superclass (Switch) that receives a float parameter to
initialize the state variable defined in the superclass
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #25
Calling super(...)
•
•
•
The constructor of a derived class MUST initialize the
state of the object from the point of view of its parent
class. Thus the first line in the constructor must be a
call to one of the constructors in the superclass using
super(...). You cannot make a later call to super(...)
because to can invoke a constructor only once!
If you do not call super(...) in the first line of the
constructor, the compiler automatically places a call to
the empty constructor of the superclass.
If there is no empty constructor in the superclass
the code will not compile!
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #26
Automatic Default Construction
•
•
•
In the previous implementation of Switch and
AdjustableSwitch we didn’t include any
constructors.
The compiler automatically added an empty (default)
constructor to each of the classes.
In addition, the compiler had put in the first line of the
empty constructor of Switch a call to the empty
constructor of AdjustableSwitch.
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #27
Automatic Default Construction
// ...in class Switch (automatically added)
public Switch() {
}
// and in class AdjustableSwitch (automatically added)
public AdjustableSwitch() {
super();
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #28
Default Construction Using Other Constructors
•
Sometimes the programmer may wish to define a
default constructor by herself, which calls other
constructors with default arguments of her choice
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #29
Default Construction - Delegation
private static final DEFAULT_POWER = 60.0f;
/**
* Constructs a new switch.
* @param power the maximal power of the switch.
*/
public Switch(float maxPower) {
if (maxPower <= 0.0f) {
throw new IllegalArgumentException();
}
this.maxPower = maxPower;
}
/**
* Constructs a switch with default power.
*/
public Switch() {
this(DEFAULT_POWER);
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #30
Overriding
•
•
In certain case, when we derive a class, we want to change
some of the functionality defined in the superclass.
Example: We want clients to be able to open a protected file
only if it is unlocked

File




RestrictedFile



The Interdisciplinary Center, Herzelia
File()
isOpen()
open()
close()
RestrictedFile(long key)
isLocked()
lock()
unlock(long key)
Lecture 8, Introduction to CS - Information Technologies
Slide #31
File Example
/**
* Part of a File implementation
*/
public class File {
// true if the file is opened
private boolean isOpen;
/**
* Checks if the file is open.
* @return true iff the file is open
*/
public boolean isOpen() {
return isOpen;
}
// other methods/variables...
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #32
File Example
/**
* Opens the file.
*/
public void open() {
// … other operations
isOpen = true;
}
/**
* Closes the file.
*/
public void close() {
// … other operations
isOpen = false;
}
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #33
RestrictedFile Example
/**
* Represents a restricted file, which can be opened
* only if it is unlocked. In order to unlock
* the file a key is needed.
*/
public class RestrictedFile extends File {
// Password for unlocking the file
private long key;
// The state of the file - locked/unlocked
private boolean isLocked;
/**
* Constructs a new restricted file.
* @param key The key to unlock the file
*/
public RestrictedFile(long key) {
this.key = key;
isLocked = true;
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #34
RestrictedFile Example
/**
* Checks if the file is locked.
*/
public boolean isLocked() {
return isLocked;
}
/**
* Locks the file.
*/
public void lock() {
isLocked = true;
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #35
RestrictedFile Example
/**
* Unlock the file. The file will be unlocked only
* if the given key matches.
* @param key the key to unlock the file
*/
public void unlock(long key) {
if (this.key == key) {
isLocked = false;
}
else
// ...
}
 So far the implementation is useless if we do not change the
implementation of open()
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #36
RestrictedFile Example
/**
* Open the file. The file will be opened only if it
* is unlocked.
*/
public void open() {
if (!isLocked()) {
super.open();
}
else
// ...
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #37
Overriding in RestrictedFile
•
•
•
RestrictedFile inherits the interface of File,
but changes the functionality of the method open().
We say that RestrictedFile overrides the
method open().
Notice the call to super.open() - we invoke the
method open() of the superclass on this object.
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #38
Rules of Overriding
•
•
•
•
When you derive a class B from a class A, the
interface of class B will be a superset of that of class A
(except for constructors)
You cannot remove a method from the interface by
subclassing (explain why...)
However, class B can override some of the methods
that it inherits and thus change their functionality.
The contract of a method states what is expected from
an overriding implementation of the method.
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #39
The Object Class
•
•
•
•
Java defines the class java.lang.Object that is defined as
a superclass for all classes.
If a class doesn’t specify explicitly which class it is derived
from, then it will be implicitly derived from class Object.
So, in the previous example, RestrictedFile was derived
from File which in turn was derived from Object.
We can depict the relationship between this classes in the
following diagram, that is called class hierarchy diagram.
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #40
Hierarchy Diagram
Object
File
RestrictedFile
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #41
The Object Class
•
•
•
•
The Object class defines a set of methods that are inherited
by all classes.
One of these is the toString() method that is used
whenever we want to get a String representation of an object.
When you define a new class, you can override the
toString() method in order to have a suitable
representation of the new type of objects as Strings.
The contract of the toString() method says that you are
expected to return a String that represents your object
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #42
Point: Example of Overriding toString()
/**
* Represents a point on a grid.
*/
public class Point {
// The coordinates of the point
private int x,y;
/**
* Constructs a new point.
* @param x,y The coordinates of the point.
*/
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return “Point: (“ + x + ”,” + y + ”)”;
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #43
Point: Example of Overriding toString()
// Example of overriding the toString() method
class PrintingPointExample {
public static void main(String[] args) {
Point p = new Point(2,3);
System.out.println(p);
//System.out.println(p.toString());
}
}
The output of the program will be:
Point: (2,3)
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #44
Polymorphism
•
•
Recall the is-a relationship induced by inheritance: A
RestrictedFile is a File which is an Object.
We can view a RestrictedFile object from 3 different
points of views:
• As a RestrictedFile. This is the most narrow point of view
(the most specific). This point of view ‘sees’ the full functionality
of the object.
• As a File. This is a wider point of view (a less specific one). We
forget about the special characteristics the object has as a
RestrictedFile (we can only open and close the file).
• As an plain Object.
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #45
Polymorphism
•
•
We view an object by using an object reference.
A variable of type ‘reference to File’ can only refer
to an object which is a File.
File f = new File();
•
But a RestrictedFile is also a File, so f can
also refer to a RestrictedFile object.
File f = new RestrictedFile();
•
The type of the reference we use determines the point
of view we will have on the object.
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #46
Polymorphism
•
If we refer to a RestrictedFile object using a
RestrictedFile reference we have the
RestrictedFile point of view - we see all the
methods that are defined in RestrictedFile and
up the hierarchy tree.

RestrictedFile f =
new RestrictedFile(12345);
f.close();
f.lock();
f.unlock(12345);
String s = f.toString();




The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #47
Polymorphism
•
If we refer to a RestrictedFile object using a
File reference we have the File point of view which lets us use only methods that are defined in
class File and up the hierarchy tree.

File f =
new RestrictedFile(12345);
f.close();
f.lock();
f.unlock(12345);
String s = f.toString();




The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #48
Polymorphism
•
If we refer to a RestrictedFile object using an
Object reference we have the Object point of
view - which let us see only methods that are defined
in class Object.

Object f =
new RestrictedFile(12345);
f.close();
f.lock();
f.unlock(12345);
String s = f.toString();




The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #49
Polymorphism
RestrictedFile





...
isOpen
isLocked
key







The Interdisciplinary Center, Herzelia
toString()
...
isOpen()
open()
close()
lock()
unlock(key)
isLocked()
Lecture 8, Introduction to CS - Information Technologies
Slide #50
Widening
•
Changing our point of view of an object, to a wider
one (a less specific one) is called widening.
File myFile;
myFile = new RestrictedFile(12345);
File reference
File point of view
RestrictedFile reference
RestrictedFile point of view
Widening
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #51
Point Example
/**
* A point on a grid.
*/
public class Point {
// ... The same implementation as before
/**
* Computes the distance from another point
* @param p The given point.
*/
public double distanceFrom(Point p) {
int dx = x-p.x;
int dy = y-p.y;
return Math.sqrt(dx*dx+dy*dy);
}
// ... more methods
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #52
Pixel Example
/**
* Represents a pixel on a graphical area.
*/
public class Pixel extends Point {
// The color of the pixel
private Color color;
/**
* Constructs a new pixel.
* @param x,y The coordinates of the pixel.
* @param color The color of the pixel.
*/
public Point(int x, int y) {
super(x,y);
this.color = color;
}
// ... more methods
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #53
Widening
•
In the following example, the method
distanceFrom() expects a ‘reference to Point’ and
gets ‘a reference to Pixel’, we are thus widening our
point of view of the Pixel object.
Pixel p1, p2;
p1 = new Pixel(2, 3, Color.yellow);
p2 = new Pixel(5, 6, Color.red);
double d = p1.distanceFrom(p2);
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #54
Heterogeneous Collections
•
•
•
•
Widening is especially useful when we want to create a
heterogeneous collection of objects.
Suppose, for example, that we want a class SwitchPanel
that represents a panel of switches. Some of the switches in the
panel are simple switches and some are adjustable switches.
Suppose also that we’ve added the method
getConsumption() in class Switch that returns the
electrical consumption of the switch (which is 0 if the switch is
off and maxPower if the switch is on)
This method was overriden in class AdjustableSwitch
(the consumption is 0 if the switch is off, or level *
maxPower / 100 if it is on).
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #55
LightBulb Example
/**
* An electronic switch that can be on/off.
*/
public class Switch {
// ... same implementation as before
/**
* Returns the electrical consumption of the switch.
*/
public float getConsumption() {
return isOn() ? maxPower : 0.0f;
}
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #56
Heterogeneous collections
/**
* An adjustable electronic switch
*/
public class AdjustableSwitch extends Switch {
// ... same implementation as before
/**
* Returns the electrical consumption of the switch.
*/
public float getConsumption() {
return super.getConsumption() * level / 100;
}
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #57
Heterogeneous collections
•
•
When implementing our SwitchPanel class, we
would like to store switches of both kinds in a single
array, so we can easily write code that operates on
both kinds of switches.
For example, suppose we want to implement a method
getConsumption() in class SwitchPanel that
will compute the total electrical consumption of all the
switches in the panel, whether they are adjustable
switches or regular switches.
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #58
Heterogeneous collections
/**
* Represents a panel of switches
*/
public class SwitchPanel {
// Holds all the switches in the building
private Switch[] switches;
// constants representing the types of switches
public final static int ADJUSTABLE_SWITCH = 1;
public final static int REGUALR_SWITCH = 0;
// here come SwitchPanel() constructor and
// getConsumption()
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #59
Heterogeneous collections
/**
* Constructs the panel according to a model file.
* @param model The name of the file that describes the panel.
*/
public SwitchPanel(String model) {
int numberOfSwitches =
a code for reading the numbers of switches
switches = new Switch[numberOfSwitches];
for (int i = 0; i < numberOfSwitches; i++) {
int switchType = a code for reading the type of the switch
float maxPower = a code for reading maxPower
if (switchType == REGULAR_SWITCH) {
switches[i] = new Switch(maxPower);
if (switchType == ADJUSTABLE_SWITCH {
switches[i] = mew AdjustableSwitch(maxPower);
}
} // for
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #60
Heterogeneous collections
/**
* Computes the total electricity consumption
* of all the switches in the panel.
*/
public float getConsumption() {
float total = 0.0f;
for (int i = 0; i < switches.length; i++) {
total += switches[i].getConsumption();
}
return total;
}
We do not care if switches[i] refers to a regular
Switch or an AdjustableSwitch, they both
know how to compute their current consumption.
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #61
Java Methods are Virtual
•
•
•
•
•
When we invoke a method on an object we always do it
through a reference
The reference can limit your viewpoint of the object
However, once a method is invoked on an object, the type of
reference used to access it is irrelevant. The implementation of
this method which is most specific will be chosen.
We say that methods in Java are virtual, which means that the
type of method which will be invoked is dependent on the type
of object (and not on the type of reference), and this type is
determined at runtime.
There are languages that use different mechanisms for method
invocation.
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #62
Type of Method is Determined at Runtime (1)
File myFile;
if (Math.random() >= 0.5) {
myFile = new File();
}
else {
myFile = new RestrictedFile(76543);
myFile.lock();
}
myFile.open();

Will the file be opened if the number tossed is
less than 0.5 ?? - NO!
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #63
Type of Method is Determined at Runtime (2)
public void maliciousMethod(RestrictedFile file) {
File workaroundReference = file;
workaroundReference.open();
// Since the file is of type RestrictedFile, this will
// invoke open() which is defined on protected files
// and not on regular files
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #64
Narrowing
•
•
•
We have seen how widening can be used in
heterogeneous collections. But if we look at all objects
from a wide point of view, and would not be able to
restore a more narrow view for some of them, there
would have been no point in having an heterogeneous
collection in the first place!
Indeed, you can restore the narrow point of view for
objects, by using casting casting.
You can use the instanceof operator to query
about the type of the object you are referencing
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #65
Narrowing Example
/**
* Locks all the restricted files in the array
* @param files The array of files to be locked
*/
public static void lockRestrictedFiles(File[] files) {
for (int i = 0; i < files.length; i++) {
if (files[i] instanceof RestrictedFile) {
RestrictedFile prot = (RestrictedFile)files[i];
prot.lock();
}
}
}
RestrictedFile
point of view
File point of view
Narrowing
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #66
Narrowing - Equivalent Example
/**
* Locks all the protected files in the array
* @param files The array of files to be locked
*/
public static void lockRestrictedFiles(File[] files) {
for (int i = 0; i < files.length; i++) {
if (doors[i] instanceof RestrictedFile) {
((RestrictedFile)files[i]).lock();
}
}
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #67
Rules of Narrowing
•
•
•
•
Narrowing let us restore a more specific point of view of an
object.
You cannot refer to an object through a RestrictedFile
reference unless this object is indeed a RestrictedFile
object
If we try to cast a File reference to RestrictedFile and
the former reference refers to a regular File, a
ClassCastException will be thrown.
In the previous example we try to cast the reference only after
we verified the object is indeed a RestrictedFile
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #68
The protected Modifier
•
Any class member (variable, method or constructor) can be
declared with one of the 4 visibility modifiers:
• private - only code of the same class in which the member has
been defined can access this member.
• (none) - default visibility - only code of a class of the same
package as that of the class in which the member has been
defined can access it.
• protected - code in a class that is in the same package or is a
subclass of the class in which the member was defined
• public - code of any class that can access the class of that
member
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #69
The protected Modifier
•
•
•
•
We declare variables as protected if they will be used often
by someone deriving our class, but we still want to hide them
from a user of our class
Avoid defining too many protected variables, we usually
want our object to be as encapsulated as possible
A protected member is included in the API of our class.
You should provide documentation comment to it
protected methods are usually useful for customizing the
behavior of our class by subclassing
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #70
Point: Example of a protected Field
/**
* Represents a point on a grid.
*/
public class Point {
/**
* The coordinates of the point.
*/
protected int x,y;
/**
* Constructs a new point.
* @param x,y The coordinates of the point.
*/
public Point(int x, int y) {
this.x = x;
this.y = y;
}
// ...
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #71
Protected Fields Example
/**
* Represents a pixel on a graphical
*/
public class Pixel extends Point {
// The color of the pixel
private Color color;
/**
* Constructs a new pixel.
* @param x,y The coordinates of
* @param color The color of the
*/
public Point(int x, int y) {
super(x,y);
this.color = color;
}
public String toString() {
return color.toString () + “
}
}
The Interdisciplinary Center, Herzelia
area.
the pixel.
pixel.
“ + super.toString();
Lecture 8, Introduction to CS - Information Technologies
Slide #72
Protected Fields Example
/**
* Draws this pixel.
*/
public void draw() {
this method will need to refer to x,y
and it will be cumbersome to do this
through access methods
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #73
The final modifier
•
•
•
•
The final modifier can be used for classes, methods and
variables, in each case it has a different meaning.
A final class can not have derived classes
A final method cannot be overriden
A final variable can be initialized only once.
• If the variable is static you must specify its value in the
declaration and it becomes a constant.
• If it is a state variable, you should either specify a value in
the declaration or in the constructor, but only there and only
once.
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #74
Heterogeneous Collections in the Java API
•
One of the most useful classes in the Java API is
java.util.Vector.
•
A vector is an oredered collection of objects.
You may add or remove objects from the vector at any
position (similar to the IntegerList exercise)
•
•
•
The size of a Vector grows and shrinks as needed to
accommodate adding and removing items after the
Vector has been created.
See the Vector API.
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #75
Heterogeneous Collections: Vector
class Cat {
public String
return new
}
}
class Dog {
public String
return new
}
}
class Mouse {
public String
return new
}
}
toString() {
String(“meaw”);
toString() {
String(“bark”);
toString() {
String(“squeak”);
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #76
Heterogeneous Collections: Vector
class MouseTrap {
public static void main(String[] args) {
Vector v = new Vector();
v.addElement(new Cat());
v.addElement(new Mouse());
v.addElement(new Dog());
v.addElement(new Mouse());
v.addElement(
new String(“it’s raining cats and dogs”));
for (int i = 0; i < v.size(); i++)
System.out.println(v.elementAt(i));
catchTheMice(v);
}
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #77
Heterogeneous Collections: Vector
public static catchTheMice(Vector v) {
int i = 0;
while (i < v.size())
if (v.elementAt(i) instanceof Mouse) {
v.removeElementAt(i);
}
else
i++;
}
}
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #78
Multiple Inheritance: Motivation
•
Recall the Switch example. Suppose we want to add
a new kind of switch that has a timeout.
Switch
AdjustableSwitch
TimeOutSwitch
But there can be adjustable switches that are time-out
switches as well, so what do we do in this case?
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies
Slide #79
Multiple Inheritance: not in Java!
•
•
•
•
•
•
We would like to define a AdjustableTimeOutSwitch class
that extends both AdjustableSwitch and
TimeOutSwitch.
If an OOP language let you define a class that is derived from
more than a single class, we say that it supports multiple
inheritance. For example, C++ does.
Multiple inheritance introduce many problems.
Java does not allow multiple inheritance. A class in Java can
have only a single superclass!
Usually you can avoid the need for multiple inheritance with
good design of the class hierarchy
There are other solutions in Java as well (interfaces)
The Interdisciplinary Center, Herzelia
Lecture 8, Introduction to CS - Information Technologies