Unit_5_-_Reusing_Classes
Unit_5_-_Reusing_Classes
Reusing Classes
• One of the most compelling
features about Java is code
reuse.
• But you’ve got to be able to do a
lot more than copy code and
change it.
• The trick is to reuse the existing
classes without soiling the existing
code.
• We'll explore two ways to
accomplish this
YR2007 2
1
3/2/2009
Reusing Classes
• First approach: You simply
create objects of your
existing class inside the new
class.
• This is called composition,
because the new class is
composed of objects of
existing classes.
• You’re simply reusing the
functionality of the code, not
its form.
YR2007 3
Reusing Classes
• Second approach: You create a
new class as a (sub)type of an
existing class.
• You literally take the form of the
existing class and add code to it
without modifying the existing
class.
• This magical act is called
inheritance, and the compiler
does most of the work.
• Inheritance is one of the
cornerstones of object-oriented
programming.
YR2007 4
2
3/2/2009
Composition
• Composition is the "has-a"
relationship we discussed back in
the very beginning.
• You simply place object
references inside new classes.
• We've been doing this with
Strings and arrays, and to a
limited extent so far with our
exercises
• The compiler doesn’t create a
default object for every
reference
– That would incur unnecessary
overhead in many cases.
YR2007 5
Composition
• If you want the references
initialized, you can do it:
1. At the point the objects are
defined. This means that
they’ll always be initialized
before the constructor is
called.
2. In the constructor for the
class.
3. Right before you actually
need to use the object.
YR2007 6
3
3/2/2009
Composition
• If you initialize when the object
references are defined, or in the
constructor, you know the
objects exist before you can
send messages to (call methods
of) the containing object.
• If you initialize right before you
actually need to use the object,
you need to include more code
to ensure the object exists when
you need them.
YR2007 7
Inheritance
• Inheritance is the ability of a new
class of object to take on all of
the properties of an existing class.
• Super Class: The original class.
• Sub Class: The new class which
inherits all of the properties of the
super class.
• The sub class can then:
– Modify the inherited properties.
– Introduce new properties.
• The terms super and sub are back
to front in the sense that the super
class generally has less than the
sub class.
YR2007 8
4
3/2/2009
Example
FASILKOM people
YR2007 9
Example
• Person class would handle the
functionality which is common to all of
the sub classes (or maybe some things
which are common to most).
• Similarly Student class would add
functionality which is common to
students
• Staff, Undergraduate and
Postgraduate would have functionality
specific to each of those categories.
• Person class and Student class are
examples of Abstract Classes.
• An abstract class is a super class which
will never be instantiated.
• An abstract class provides a template
for its sub classes.
YR2007 10
5
3/2/2009
Inheritance in Java:extends
• In Java in a class inherits from a super
class then the extends clause is used to
specify the name of the super class.
• Syntax is: class subclass extends
superclass
• Methods in the sub class which will have
exactly the same implementation as in
the parent class are not defined in the
sub class.
• Methods in the sub class which have a
different implementation as in the super
class must be redefined.
• Methods which are not provided in the
super class but are required for the sub
class must be defined.
YR2007 11
Example
public class
UndergraduateClass
extends StudentClass
{ ...
}
public class
PostgraduateClass extends
StudentClass
{ ...
}
YR2007 12
6
3/2/2009
Inheritance in Java:
protected variables and methods
YR2007 13
Inheritance in Java:
protected variables and methods
• Syntax is: protected
datatype variablename;
• Preferably should never be
used because it makes the
implementation of the sub
classes dependent upon the
implementation of the super
class.
• Result is a modification to
the super class would mean
that all of the descendent
class will need to be
modified.
YR2007 14
7
3/2/2009
Class Relationships
• “is a”
– Class A is a Class B
– Use Inheritance
• “has a”
– Class A has a Class B
– Known as aggregation.
– Class A will contain one or more
object(s) of class B.
• Examples:
– Circle is a Shape
– Circle has a point (i.e. its centre
coordinate).
YR2007 15
8
3/2/2009
Explicitly Referring to a
Superclass:super
• We often need to invoke a
method in the super class
explicitly.
• Usually this occurs in methods
which are overriding a method
in the super class.
• In other words:
– Perform actions unique to the sub
class and then
– invoke the equivalent method in
the super class (to gain the
functionality of the super class).
• Syntax is:
super.superClassMethod();
YR2007 17
Example
public class UndergraduateClass
extends StudentClass
{ ...
public UndergraduateClass(
String name, String stdno)
{ super( name);
int frog;
this.stdno = new String
(stdno);
...
}
...
public void whateverMethod()
{ super.superClassMethod();
...
}
}
YR2007 18
9
3/2/2009
Inheritance/Aggregation Revisited
• The classes of objects which
communicate with each
other via message passing
must share some form of
relationship with each other.
• Three basic types of
relationship:
– Inheritance:
• One class is a descendent of another
class.
• Uses polymorphism, method
overloading or direct references to the
super class to communicate.
Communication is one way, from child
to parent (sound familiar!!).
YR2007 19
Inheritance/Aggregation Revisited
– Aggregation:
• One Class is declared as a
class field within the other
class. or is declared as
local to a method.
• Communication is one
way (most of the time?),
from class to class field.
– Other:
• An object instance of one
class is returned by a
method in another class.
YR2007 20
10
3/2/2009
UML: Inheritance
• The Is A relationship between two
classes.
• Class A Is A Kind of Class B.
• Also known as
specialisation/generalisation.
• Example:
• An undergraduate student is a kind of
student.
• UndergraduateClass Is A Kind of
StudentClass.
• UnderGraduateClass is a more
specialised form of StudentClass.
• StudentClass is a more generalised form
of UndergraduateClass
• In UML a link with a hollow arrow head
represents inheritance.
YR2007 21
YR2007 22
11
3/2/2009
UML: Aggregation
• The Has A relationship between two
classes.
• Class A Has A Class B.
• Class B is a part of class A.
• Class B can be a part of many other
classes.
• Example:
• A motor vehicle has an engine.
• MotorVehicleClass Has A EngineClass.
• In UML a link with a hollow diamond
represents an aggregation
relationship.
YR2007 23
Name hiding
• Overloaded methods (same
name, different args) are not
hidden
– Parent has
public String alter(int i, char
c)
– Subclass has
public String alter(int f,
String s)
– Either of these can be freely
called for an object of the
subclass type
• Not all languages work this
way!
YR2007 24
12
3/2/2009
YR2007 25
YR2007 26
13
3/2/2009
YR2007 27
YR2007 28
14
3/2/2009
Incremental Development
• Inheritance supports
incremental development
by allowing you to
introduce new code
without causing bugs in
existing code
– You don’t even need the
source code for the methods
in order to reuse the code
YR2007 29
Incremental Development
• Remember that underneath it
all, inheritance is meant to
express a relationship that says
“This new class is a type of that
old class.”
– Your program should not be
concerned with pushing bits
around
– Instead, with creating and
manipulating objects of various
types to express a model in the
terms that come from the problem
space
YR2007 30
15
3/2/2009
YR2007 31
Final Data
• Final data is a constant
• A field that is both static
and final not only cannot
be changed, but there is
only one copy of it
– and this is how you usually
do it
static final double pi =
3.1415926535;
– why would you want multiple
copies of that?
YR2007 32
16
3/2/2009
Final Data
• When using final with object
references rather than primitives
the meaning gets a bit confusing.
• With an object reference, final
makes the reference a constant
– Once the reference is initialized to
an object, it can never be changed
to point to another object
• No assignments allowed to that
variable
– However, the object itself can be
modified!
YR2007 33
final methods
• There are two reasons for final
methods.
– The first is to put a “lock” on the
method to prevent any inheriting
class from changing its meaning.
• This is done for design reasons when
you want to make sure that a
method’s behavior is retained during
inheritance and cannot be
overridden.
– The second reason for final methods
is efficiency.
• If you make a method final, you are
allowing the compiler to turn any calls
to that method into inline calls.
YR2007 34
17
3/2/2009
final classes
• When you say that an entire class
is final, you state that you don’t
want to inherit from this class or
allow anyone else to do so.
– For some reason the design of your
class is such that there is never a
need to make any changes
– For safety or security reasons you
don’t want subclassing
– Let's look at java.lang.Math
YR2007 35
final classes
• Data members of a final class
can be final or not, as you
choose
– The same rules apply to final for data
members regardless of whether the
class is defined as final.
• Because it prevents inheritance,
all methods in a final class are
implicitly final
– There’s no way to override them.
– The compiler has the same
efficiency options as it does if you
explicitly declare a method final.
YR2007 36
18
3/2/2009
YR2007 37
YR2007 38
19
3/2/2009
YR2007 39
YR2007 40
20
3/2/2009
YR2007 41
YR2007 42
21
3/2/2009
YR2007 44
22
3/2/2009
//: c06:Beetle.java
// The full process of initialization.
class Insect {
public int i = 5;
public int j = 10;
Insect() {
}
public static int x1 = print("Mesg A: static
Insect.x1 initialized");
static int print(String s) {
System.out.println(s);
return 20;
}
}
YR2007 46
23
3/2/2009
YR2007 47
24