0% found this document useful (0 votes)
11 views16 pages

301lec06mj

The document covers key concepts in object-oriented programming, specifically focusing on interfaces, abstract classes, and inheritance in Java. It explains how to define interfaces, the use of copy constructors and cloneable interfaces, and the importance of polymorphism and dynamic binding. Additionally, it discusses the principles of generalization and specialization in class hierarchies, including method overriding and the implications of hiding inherited methods.

Uploaded by

daniel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views16 pages

301lec06mj

The document covers key concepts in object-oriented programming, specifically focusing on interfaces, abstract classes, and inheritance in Java. It explains how to define interfaces, the use of copy constructors and cloneable interfaces, and the importance of polymorphism and dynamic binding. Additionally, it discusses the principles of generalization and specialization in class hierarchies, including method overriding and the implications of hiding inherited methods.

Uploaded by

daniel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Today:

CMPUT 301: Lecture 06


• Examles in UML and Java of
Interfaces, Abstract classes and Inheritance
1. Writing a class definition without
implementation: “interface”
Lecturer: Martin Jagersand 2. Leaving out particular implementations
Department of Computing Science
(abstract methods or classes)
University of Alberta
Notes based on previous courses by 3. Extending functionality by subclassing
Ken Wong, Eleni Stroulia (inheritance)
Zach Dodds, Martin Jagersand
4. Comparison to (last lecture topic): adding
functionality by composition
2

Copying Objects Copying Objects

• Copy constructor: • Cloneable interface:


Color red = new Color( 255, 0, 0 ); Color red = new Color( 255, 0, 0 );
Color redCopy = new Color( red ); Color redClone = red.clone();

• public class Color { • public interface Cloneable {


private int red; public Cloneable clone();
private int green; }
private int blue;
… • public class Color implements Cloneable {
public Color( Int R, G, B) {<initialize>} private int red;
private int green;
• public Color( Color other ) { private int blue;
red = other.red; …
blue = other.blue; public Cloneable clone() {
green = other.green; return new Color( red, green, blue );
} }
} }
3 4

1
Comparison Interfaces
• public class Location {
private int x;
• An interface can specify a contract between
private int y; interacting or associated objects.

public boolean equals( Location other ) {
if (this == other)
• For example, a server object’s class could satisfy
return true; an interface (a list of provided methods or
else
return x == other.x && y == other.y; services).
}
… • A client object could use any object for the server
}
role whose class implements this interface.

5 6

Interfaces Interfaces

• An interface represents a “capability”.


• Use interfaces to increase flexibility when
associating objects.

7 8

2
Interfaces Interfaces
• public interface Sequenced { • public class Counter implements Sequenced {
public void next(); …
public void reset(); public Counter() { … }
} public void next() { … }
// objects of classes that implement this interface public void reset() { … }
// can be “stepped” forward in sequence …
}

• public class ImageSequence implements Sequenced {



public ImageSequence() { … }
public void showIn( Frame frame ) { … }

public void next() { … }
public void reset() { … }

}
9 10

Interfaces Private Data and Methods


• public class Clock { • import Sequenced;
… import Message;
public void connectTo( Sequenced target ) { … } …
// any object whose class implements the // version 1
// Sequenced interface can be passed in public class SimpleCounter implements Sequenced {
… // instance variables
} private int value;
private Message message;

// constructor
public SimpleCounter( int initValue ) {
value = initValue;
}

// private method
private void update() {
if (message != null)
message.setText( String.valueOf( value ) );
11 } 12

3
Private Data and Methods Generalization
• // public methods
• Look for conceptual commonalities in the
public void next() {
value++;
abstractions:
update();
}
– common attri but es
– e.g., all vehicles have ?
public void reset() {
value = 0; – common acti ons
update();
} – e.g., all vehicles can ?

public void connectTo( Message msg ) {


message = msg;
update();
}
}

13 14

Example
Designing a Class Hierarchy
Designing a Class Hierarchy

15 16

4
Generalization Generalization

• Java interface: • Inheritance:


– set of met hods t hat is i mpl e ment ed by cl asses – generalize about met hod si gnat ures, met hod
satisfyi ng t he i nt erface i mpl e ment ations, and dat a
– this i nt erface is common t o t he i mpl e menting cl asses – a base cl ass (or supercl ass) defi nes t he shared i nt erface and
– this i nt erface represents a “capabilit y” common t o t he i mpl e ment ation
i mpl e ment i ng cl asses – a deri ved cl ass (or subcl ass) is endo wed wi t h t he i nt erface
– but onl y generalizes about met hod si gnat ures and i mpl e ment ation of its base cl ass

17 18

Specialization Why Inheritance?

• Inheritance: • Programming:
– “is a” rel ationshi p bet ween abstractions or cl asses – fact or out repetiti ous, reusabl e code
– e.g., a bus “is a” land-based vehicle • Design:
– a deri ved cl ass can ext end t he base cl ass by addi ng – applicati on do mai n modeli ng
ne w dat a and met hods
• Software engineering:
– ma ke syst e ms flexi bl e and ext ensi bl e

19 20

5
Sharing Implementation Sharing Implementation
• public class Number { • public class Cycler {
private int value; private int value;
private TextBox textBox; private int base;
private TextBox textBox;
public Number( int initValue ) { … }
public Number() { … } public Cycler( int base, int initValue ) { … }
public void showIn( TextBox tbox ) { … } public Cycler( int base ) { … }
public void show() { … } public Cycler() { … }
public void next() { … } public void showIn( TextBox tbox ) { … }
public void reset() { … } public void show() { … }
public int value() { … } public void next() { … }
} public void reset() { … }
public int value() { … }
}

21 22

Sharing Implementation Sharing Implementation

• Co mmonalities: • Di fferences:
– data – data
– value – base
– textBox
– methods – methods
– showIn( … ) – constructors
– show() – next()
– reset()
– value()

23 24

6
Sharing Implementation Inheriting Methods and Data
• public class DisplayableNumber { // version 1
• Cycler “is a” DisplayableNumber private TextBox textBox;
protected int value;
– a Cycl er obj ect can be used wherever a
Di s playabl e Nu mber obj ect can be used public DisplayableNumber( int initValue ) { … }
public void showIn( TextBox tbox ) { … }
– a Cycl er obj ect responds t o t he sa me calls ( messages) public void show() { … }
as a Displ ayabl e Nu mber obj ect public void reset() { … }
public int value() { … }
– DisplayableNumber number = new Cycler();
}

25 26

Inheriting Methods and Data Inheriting Methods and Data


• public class Number extends DisplayableNumber { • public class DisplayableNumber { // version 1
public Number( int initValue ) { … } private TextBox textBox;
public Number() { … } private int value;
public void next() { value++; }
} public DisplayableNumber( int initValue ) { … }
public void showIn( TextBox tbox ) { … }
• public class Cycler extends DisplayableNumber { public void show() { … }
private int base; public void reset() { … }
public int value() { … }
public Cycler( int base, int initValue ) { … }
public Cycler( int base ) { … } protected void setValue( int v ) { value = v; }
public Cycler() { … } protected int getValue( return value; }
public void next() { … } }
}

27 28

7
Inheritance Constructors

• Javahasonlysingleinheritance. • Constructors are called bottom-up but executed


• Inheritance hierarchy is a tree. top-down.
• Root class is java.lang.Object.
• Final classes cannot be extended.
• Mixin classes.

29 30

Constructors Default Constructor


• public class Number extends DisplayableNumber {

• If Number does not define a constructor, Java implicitly inserts:
public Number( int initValue ) { implicitly inserts:
super( initValue ); // default constructor
// explicit call to super( … ); // Number inherits from DisplayableNumber
// must be first statement in constructor; public Number() {
// superclass data is initialized super();
} }

} • However, if DisplayableNumber does not have
• public class DisplayableNumber { the required:
… // no-argument constructor
public DisplayableNumber( int initValue ) { public DisplayableNumber() {
// implicitly inserted call to super(); …
value = initValue; }
}

31
• Compilation error. 32
}

8
Shadowing Data Replacing Inherited Methods
• public class DisplayableNumber {
protected int value; // 2, 3 • A subclasscanredefineaninheritedmethodbyoverridingit.

}
overriding it.

• public class Number extends DisplayableNumber {


• The overriding method has the same signature.
private int value; // 0, 1
… • Overriding != overloading.
public void test() {
value = 0;
this.value = 1;
super.value = 2;
((DisplayableNumber)this).value = 3;

// two “value”s in the Number object


}
} 33 34

Replacing Inherited Methods Replacing Inherited Methods


• import Number;

public class RestartCounter extends Number {


private int original;

public RestartCounter( int initValue ) {


super( initValue );
original = initValue;
}
public RestartCounter() {
super( 0 );
original = 0;
}
// override (replace) ...
public void reset() {
value = original;
}
}
35 36

9
Extending Inherited Methods Extending Inherited Methods
• public class Cycler extends DisplayableNumber {
• To extend an inherited method, override it, and private int base;
also call it (to do part of the work). …
public void reset() {
// call overridden method;
// does not need to be first statement
super.reset();
value = value % base;
}
}

37 38

Hiding Inherited Methods Hiding Inherited Methods

• To prevent an inappropriate superclass method • Too much hiding probably means a violation of
from appearing in a subclass, hide it by: the “is a” relationship between the superclass and
– overri di ng t he met hod, or subclass.
– usi ng aggregation, or
– revisi ng t he i nheritance hi erarchy

39 40

10
Hiding Inherited Methods Hiding Inherited Methods

• Suppose: • Suppose:
– cl ass Dog – cl ass Windo w
has bar k(), fet ch() has show(), hi de(), move(), resi ze()
– cl ass Cat inherits from Dog, – cl ass Fi xedSi ze Wi ndo w
but hi des bar k(), fet ch(), inherits from Wi ndo w
and adds purr() but hi des resi ze()
• Cat “is a” Dog? • FixedSizeWindow “is a” Window?

41 42

Hiding Inherited Methods Hiding Inherited Methods


• public class Rectangle {
• Suppose: …
public Rectangle( Shape s ) { … }
– cl ass Vect or public void setLocation( Location p ) { … }
has addEl e ment(), i nsert El e ment At(), el e ment At(), public void setShape( Shape s ) { … }
public void draw() { … }
re move El e ment At(), … public void clear() { … }
public void rotate() { … }
– cl ass Pr oj ect Tea m …
inherits from Vect or }

• ProjectTeam “is a” Vector? • public class Square extends Rectangle {


// want to hide setShape()
}

• Square “is a” Rectangle?


43 44

11
Overriding the Method Using Aggregation
• public class Square extends Rectangle { • public class Square {
… private Rectangle rect;
public void setShape( Shape s ) {
public Square( int side ) {
// should not implement
rect = new Rectangle(
}
new Shape( side, side ) );
… }
}
public void setSide( int newSide ) {
rect.setShape(
new Shape( newSide, newSide ) );
}


// Square “has a” Rectangle
}

45 46

Revising the Inheritance Hierarchy Dynamic Binding


• public class Quadrilateral {
… • Binding refers to how a method is selected to be
public Quadrilateral( Shape s ) { … }
public void setLocation( Location p ) { … }
run.
public void draw() { … }
public void clear() { … } • In static binding, the selection is known and made
public void rotate() { … }
}
at compile time.

• public class Rectangle extends Quadrilateral {


• In dynamic binding, the selection is made at run
public Rectangle( Shape s ) { … }
public void setShape( Shape s ) { … }
time, depending on the type of the object.
}

• public class Square extends Quadrilateral {


public Square( int side ) { … }
public void setSide( int side ) { … }
} 47 48

12
Dynamic Binding Dynamic Binding
• public class Base {
// default implementation • The object does the right thing, even if the calling
public void op() { … }
}
code does not know its type.
• public class Derived1 extends Base {

• Interrelated concepts:
}
// does not override op() inheritance, type casting, method overriding,
• public class Derived2 extends Base { abstract methods.
// override ...
public void op() { … } • Polymorphism.
}

• Base base;
base = new Derived1(); // implicit widening cast
base.op(); // calls op() in Base
base = new Derived2(); // implicit widening cast
base.op(); // calls op() in Derived2 49 50

Overriding is not Shadowing Abstract Methods


• class A {
int i = 1; • The base class method to be overridden can be:
int f() { return i; }
} – a met hod wi t h a default i mpl e ment ation
• class B extends A { – a met hod wi t h an e mpt y body
int i = 2; // shadow
int f() { return -i; } // override – an abstract met hod
}
• public class Test {
(no i mpl e ment ation,
public static void main( String args[] ) { subcl ass responsi bility t o i mpl e ment)
B b = new B();
// b.i is 2
// b.f() returns -2
A a = (A)b;
// a.i is 1
// a.f() returns -2, “dynamic binding”
}
} 51 52

13
Example:
Abstract Classes
Abstract class
• A class which is explicitly designed to be the superclass abstract class Shape {

for a set of dependent classes, but which does not itself


Color color;
provide sufficient functionality for independent use, is int x,y;
known as an abstract base class (ABC).
void setColor(Color newColor) {
color = newColor;
• A method in a ABC which must be overridden in each draw(); }
descendent class (and will fault if not) is known as an
void setXY(int xCoord, int yCoord) {
abstract method
x = xCoord; y = yCoord;
draw(); }

53
abstract void draw(); } 54

Example: Shape why abstract classes?


Comments
• No instances of Shape can be created
1. All Shape subclasses exhibit the same behavior
• Two methods with default implementations
2. This behavior is specified at the abstract class level,
• One abstract method and then all shapes are manipulated as Shapes except
• All subclasses of Shape must override draw from their construction
3. When constructed, each shape will be of a particular
• There can be variables of class Shape; at run time
subtype of Shape
they will be constructed as instances of a 4. At run time, when a particular behavior is required of a
particular subclass of Shape particular object, this behavior will be implemented
polymorphically depending on the actual class of the
object
55 56

14
Designing a Class Hierarchy Designing a Class Hierarchy

• Need to have a logical, rational explanation for


the organization of the hierarchy.

57 58

Designing a Class Hierarchy Designing a Class Hierarchy

59 60

15
Designing a Class Hierarchy Designing a Class Hierarchy

61 62

End

• What did I learn today?


• What questions do I still have?

63

16

You might also like