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

Unit_5_-_Reusing_Classes

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

Unit_5_-_Reusing_Classes

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

3/2/2009

Unit 5 – Reusing Classes


Faculty of Computer Science 2007
Universitas Indonesia

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

• Variables declared as private


cannot be accessed in any other
class.
• This is also true for sub classes. In
other words a sub classes cannot
refer to any variables in the super
class which have been declared as
private.
• Variables and methods which are
declared as protected:
– Can be accessed by any descendent
of the class.
– Cannot be accessed by a class which is
not a descendent of the class.

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

The Use of super with Constructors


• The first line of a constructor can
be used to explicitly call a super
class constructor.
• To explicitly refer to a particular
constructor in the super class we
simply use the syntax:
super(superClassConstructorArgs);
• If the first line of the constructor
does not contain a call to a super
class constructor then the default
constructor for the super class is
called.
• Note: the first line means the line
immediately after the method
header.
YR2007 16

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

Fasilkom people Example

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

Combining Composition and Inheritance

• It is very common to use


composition and inheritance
together.
– In fact, you will probably have very
few classes that don't include Strings
or arrays, and everything inherits
from Object, so you practically
always do!
• However, in using composition,
you need to remember to
initialize the member objects
– Otherwise: Null pointer exceptions !

YR2007 25

Choosing composition vs.


inheritance
• Both composition and
inheritance allow you to
place subobjects inside
your new class.
• What are the differences
between the two
approaches, and when do
you choose one over the
other?

YR2007 26

13
3/2/2009

Choosing composition vs.


inheritance
• Composition is generally used
when you want the features of
an existing class inside your
class, but not its interface.
– You embed an object so that you
can use it to implement
functionality in your new class
– The user of your new class sees the
interface for the new class, not the
interface of the embedded object
• You embed private objects of
existing classes inside your new
class.

YR2007 27

Choosing composition vs.


inheritance
• It's usually obvious whether
the relationship is is-a or
has-a
– A GradStudent is-a Student
– A Student has-a Schedule
– A HomeAddress is-an
Address
– An Address has-a Type

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

The final keyword


• Java’s final keyword has slightly
different meanings depending
on the context, but in general it
says “This cannot be changed.”
– You might want to prevent
changes for two reasons: design or
efficiency.
– Because these two reasons are
quite different, it’s possible to
misuse the final keyword.
• final can be used for data,
methods, and classes

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

Initialization and class loading


• In traditional languages,
programs are loaded all at
once as part of the startup
process
• This is followed by
initialization
• Then the program begins

YR2007 37

Initialization and class loading


• In Java, the compiled
code for each class exists
in its own separate file.
– the .class files we've already
seen
• That file isn’t loaded until
the code is needed.

YR2007 38

19
3/2/2009

Initialization and class loading


• In general, you can say
that “Class code is loaded
at the point of first use.”
• This is often not until the first
object of that class is
constructed, but loading
also occurs when a static
field or static method is
accessed.

YR2007 39

Initialization and class loading


• The point of first use is also
where the static initialization
takes place.
• All the static objects and the
static code block will be
initialized in textual order (that
is, the order that you write them
down in the class definition) at
the point of loading.
– The statics, of course, are initialized
only once.

YR2007 40

20
3/2/2009

Initialization with inheritance


• We're going to look at an
example from TIJ, Beetle.java
• The first thing that happens
when you run Java on Beetle is
that you try to access
Beetle.main( ) (a static method),
so the loader goes out and
finds the compiled code for the
Beetle class (this happens to be
in a file called Beetle.class).

YR2007 41

Initialization with inheritance


• In the process of loading
Beetle.class, the loader notices
that it has a base class (that’s
what the extends keyword
says), which it then loads.
– This will happen whether or not
you’re going to make an object of
that base class.
• If the base class has a base
class, that second base class
would then be loaded, and so
on.

YR2007 42

21
3/2/2009

Initialization with inheritance


• Next, the static initialization
in the root base class (in
this case, Insect) is
performed, and then the
next derived class, and so
on.
– This is important because the
derived-class static
initialization might depend
on the base class member
being initialized properly.
YR2007 43

Initialization with inheritance


• At this point, the necessary
classes have all been loaded so
the object can be created.
– First, all the primitives in this object
are set to their default values and
the object references are set to
null.
– Then the base-class constructor will
be called.
• In this case the call is automatic,
but you can also specify the base-
class constructor call (as the first
operation in the Beetle( )
constructor) using super.

YR2007 44

22
3/2/2009

Initialization with inheritance


• The base class construction
goes through the same
process in the same order
as the derived-class
constructor.
• After the base-class
constructor completes, the
instance variables are
initialized in textual order.
• Finally, the rest of the body
of the constructor is
executed.
YR2007 45

//: 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

public class Beetle extends Insect {


public int k = print("Mesg B: Beetle.k
initialized");
public static int x2 = print("Mesg C: static
Beetle.x2 initialized");
public static void main(String[] args) {
Beetle b = new Beetle();
System.out.println("Insect.x1 + Beetle.x2
= "+ (Insect.x1 + Beetle.x2));
System.out.println("b.i + b.j + b.k = " +
(b.i + b.j + b.k));
}
} ///:~

YR2007 47

24

You might also like