






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Answer: Inheritance. “ “Inheritance is new code that reuses old code Inheritance is new code that reuses old code. Polymorphism is old code that reuses new ...
Typology: Study notes
1 / 12
This page cannot be seen from the preview
Don't miss anything!







"Question: What is the object oriented way ofgetting rich?Answer: Inheritance.““Inheritance is new code that reuses old code
Inheritance is new code that reuses old code.
Polymorphism is old code that reuses new code.”
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
1
Explanation of inheritance.
Using inheritance to create a SortedIntList.
Explanation of polymorphism.
Using polymorphism to make a more genericUsing
polymorphism to make a more generic
List class.
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
3
Encapsulation
abs
ac o ,
o
a o
d
g
Inheritance
code reuse specialization "New code using old
New code using old
code."
Polymorphism
Polymorphism
where X is
different
depending on the type of
where X is
different
depending on the type of
object
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
Old
code using new code.
Obj
t
i
t d
i
l
d
t
Object oriented programming leads to programs that are models
ti
d l
f thi
i
th
l
ld
There are many types of relationships between
There are many types of relationships between the things in the models
chess piece has a position
chess piece moves (changes position)
Inheritance and Polymorphism
5
a
rook is a type of chess piece
Objects are often made up of many parts or have sub data.
This “has-a” relationship is modeled by composition
p
Encapsulation captures this conceptEncapsulation
captures this concept
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
Another type of relationship found in the real world
“is-a” usually denotes some form of
is a
usually denotes some form of
specialization
it is not the same as
“has-a”
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
7
it
is not the same as
has-a
The “is-a” relationship, and the specialization that accompanies it, is modeled in objectoriented languages via
inheritance
Classes can inherit from other classes
things being modeled
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
If
l
h
d
d
t i
l d
th
If a class header does not include the extends clause the class extends the Obj
t
class by default
Obj
ect
class
by default
public class Die
i
ll
l
i
s an ancestor to all classes
th
l
other class
A class extends exactly one other class
multiple
inheritance.
Java does not support this directly,
th
it
I t
f
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
13
rather it uses
I
nterfaces
.
any method that is not
final
may be
overridden by a descendant class
y
same signature as method in ancestor
may not reduce visibility
may not reduce visibility
may use the original method if simply want to
dd
b h
i
t
i ti
add more behavior to existing
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
What is output when the
main
method is run?
public class Foo{
public static void
main(String[] args){
Foo f1 = new Foo();System.out.println( f1.toString() );
}
}}
null
null
C. Unknown until code is actually run.D. No output due to a syntax error.E. No output due to a runtime error.
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
15
p
l
l
ll d
Declare a class called
ClosedShape
Object
's version of
toString
Possible sub classes of
ClosedShape
Square
Possible hierarchy
ClosedShape
<
Rectangle
<
Square
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
ClosedShape
<
Rectangle
<-
Square
p
ublic
class
ClosedShape
p
p
{
private
double
myX;
private
double
myY;
public
ClosedShape()
public
ClosedShape()
{
this(0,0);
}
public
ClosedShape
(double
x,
double
y)
{
myX
x;
{
myX
=
x;
myY
=
y;
}
bli
i
i
()
public
String
toString()
{
return
"x:
"
getX()
"
y:
"
getY();
}
public
double
getX(){
return
myX;
}
p
g
y
public
double
getY(){
return
myY;
}
}//
Other
methods
not
shown
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
17
Constructors handle initialization of objects
Constructors handle initialization of objects
When creating an object with one or more ancestors (everytype except Object) a chain of constructor calls takes place
yp
p
j
)
p
The reserved word
super
may be used in a constructor to
call a one of the parent's constructors
t b
fi
t li
f
t
t
if no parent constructor is explicitly called the default, 0parameter constructor of the parent is calledp
p
If a parent constructor is called another constructor in thesame class ma
no be called
same class may no be called
super();this();
allowed. One or the other, not both
Inheritance and Polymorphism
public class Rectangle extends ClosedShape{
private double myWidth;private double myHeight;public Rectangle( double x, double y,
double width, double height )
g
{
super(x,y);// calls the 2 double constructor in// ClosedShape
p
myWidth = width;myHeight = height;
}
// other methods not shown
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
19
}
public
class
Rectangle
extends
ClosedShape
{
private
double
myWidth;
private
double
myHeight;
public
Rectangle()
{
this(
0);
{
this(0, 0);
} public
Rectangle(double
width,
double
height)
{
myWidth
=
width;
myHeight
=
height;
} public
Rectangle(double
x,
double
y,
double
width
double
height)
double
width, double
height)
{
super(x,
y);
myWidth
=
width;
myHeight
=
height;
} public
String
toString()
{
return
super.toString()
"
width
"
myWidth
"
height
"
myHeight;
}
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
}
}
public
accessible to all classes
private
y
classes.
protected
ibl
b
l
ithi
th
k
d
ll
p
ackage
and all
descendant classes
Instance variables
should
be private
p
protected methods are used to allow descendant classes to modify instance variables in ways other
l
't
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
25
classes can't
In general it is good practice to make instance variables privateinstance variables private
if
thi k d
d
t
ill
d t
them or modify them provide protected methodsto do thisto do this
Why?
Consider the following example
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
public class GamePiece{
private Board myBoard;private Position myPos;private Position myPos;// whenever my position changes I must
y p
g
// update the board so it knows about the changeprotected void alterPos( Position newPos ){
Position oldPos = myPos;myPos = newPos;myPos
newPos;
myBoard.update( oldPos, myPos );
}
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
27
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
Assume we want to have a list of ints, but that the ints must always be maintained inascending order
[-7, 12, 37, 212, 212, 313, 313, 500]sortedList.get(0)
returns the min
sortedList.get( list.size() – 1 )
returns the max
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
29
Do we have to write a whole new class?
Assume we have an
IntList
class.
Which of the following methods would have to be changed?to be c a ged
add(int value)int get(int location)int get(int location)String toString()int size()int size()int remove(int location)
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
First attempt
Problem?
solving with
protected
What
protected
really means
What
protected
really means
solving with insert method
double edged sort
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
31
What about this method?
void
insert(int
location,
int
val)
What about this method?
void
insertAll(int
location
void
insertAll(int
location,
IntList
otherList)
SortedIntList
is not the cleanest
SortedIntList
is
not the cleanest
application of inheritance.
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
ClosedShape s = new ClosedShape(1,2);System.out.println( s.toString() );s
ne
Rectangle(
3
4
s = new Rectangle(2, 3, 4, 5);System.out.println( s.toString() );s = new Circle(4, 5, 10);s
new Circle(4, 5, 10);
System.out.println( s.toString() );s = new ClosedShape();System.out.println( s.toString() );
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
37
To determine if a method is legal the compiler looks in theclass based on the declared type
if it finds it great, if not go to the super class and look there
and the method was never found. (Compile error)
To determine which method is actually executed the runTo
determine which method is actually executed the run
time system
methodmethod
repeat until a version is found
Is it possible the runtime system won’t find a method?
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
38
What is output by theWhat is output by thecode to the right whenrun?
public
class
Animal{
public
String
bt(){
return
"!";
}
}
public
class
Mammal
extends
Animal{
public
String
bt(){
return
"live";
}
}
public
class
Platypus
extends
Mammal{
public
String
bt(){
return
"egg";}
}
} Animal
a
=
new
Animal();
Animal
a
=
new
Platypus();
Mammal
m
=
new
Platypus();
System.out.print(
a1.bt()
);
System.out.print(
a2.bt()
);
System.out.print(
m1.bt()
);
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
39
I h
it
ll
t
d l
Inheritance allows programs to model relationships in the real world
if th
f ll
th
d l it
b
i
to write
Inheritance allows code reuse
Inheritance allows code reuse
programs)programs)
Polymorphism allows code reuse in another way (We will explore this next time)
y (
p
Inheritance and polymorphism allow programmers to create
g
eneric algorithms
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
40
p
g
g
g
f th
l
f OOP i
th
t
f
One of the goals of OOP is the support of code reuse to allow more efficient programdevelopmentdevelopment
If a algorithm is essentially the same, but the code would vary based on the data typecode would vary based on the data typegenericity allows only a single version of thatcode to existcode to exist
templates
in Java, there are 2 ways of doing thisin
Java, there are 2 ways of doing this
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
41
public Object[] createASet(Object[] items){
/*pre: items != null, no elementsof items = nullpost: return an array of Objectspost:
return an array
of Objects
that represents a set of the elementsin items. (all duplicates removed)
/
*/
{5, 1, 2, 3, 2, 3, 1, 5} -> {5, 1, 2, 3} CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
String[]
sList
=
{"Texas",
"texas",
"Texas",
"Texas",
"UT",
"texas"};
Object[]
sSet
=
createASet(sList);
for(int
i
=
0;
i
<
sSet.length;
i++)
System.out.println(
sSet[i]
);
Object[]
list
=
{"Hi",
1,
4,
3.3,
true,
new
ArrayList(),
"Hi",
3.3,
4};
Object[]
set
createASet(list);
Object[]
set
=
createASet(list);
for(int
i
=
0;
i
<
set.length;
i++)
System.out.println(
set[i]
);
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism
43
CS 307 Fundamentals ofComputer Science
Inheritance and Polymorphism