Presentation is loading. Please wait.

Presentation is loading. Please wait.

CMPUT 301: Lecture 06 Interfaces, Abstract classes and Inheritance

Similar presentations


Presentation on theme: "CMPUT 301: Lecture 06 Interfaces, Abstract classes and Inheritance"— Presentation transcript:

1 CMPUT 301: Lecture 06 Interfaces, Abstract classes and Inheritance
Lecturer: Martin Jagersand Department of Computing Science University of Alberta Notes based on previous courses by Ken Wong, Eleni Stroulia Zach Dodds, Martin Jagersand

2 Today: Examles in UML and Java of
Writing a class definition without implementation: “interface” Leaving out particular implementations (abstract methods or classes) Extending functionality by subclassing (inheritance) Comparison to (last lecture topic): adding functionality by composition

3 Copying Objects Copy constructor: Color red = new Color( 255, 0, 0 ); Color redCopy = new Color( red ); public class Color { private int red; private int green; private int blue; … public Color( Int R, G, B) {<initialize>} public Color( Color other ) { red = other.red; blue = other.blue; green = other.green; } }

4 Copying Objects Cloneable interface: Color red = new Color( 255, 0, 0 ); Color redClone = red.clone(); public interface Cloneable { public Cloneable clone(); } public class Color implements Cloneable { private int red; private int green; private int blue; … public Cloneable clone() { return new Color( red, green, blue ); } }

5 Comparison public class Location { private int x; private int y; … public boolean equals( Location other ) { if (this == other) return true; else return x == other.x && y == other.y; } … }

6 Interfaces An interface can specify a contract between interacting or associated objects. For example, a server object’s class could satisfy an interface (a list of provided methods or services). A client object could use any object for the server role whose class implements this interface.

7 Interfaces An interface represents a “capability”.
Use interfaces to increase flexibility when associating objects.

8 Interfaces

9 Interfaces public interface Sequenced { public void next(); public void reset(); } // objects of classes that implement this interface // can be “stepped” forward in sequence

10 Interfaces public class Counter implements Sequenced { … public Counter() { … } public void next() { … } public void reset() { … } … } public class ImageSequence implements Sequenced { … public ImageSequence() { … } public void showIn( Frame frame ) { … } … public void next() { … } public void reset() { … } … }

11 Interfaces public class Clock { … public void connectTo( Sequenced target ) { … } // any object whose class implements the // Sequenced interface can be passed in … }

12 Private Data and Methods
import Sequenced; import Message; … // version 1 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 ) ); }

13 Private Data and Methods
// public methods public void next() { value++; update(); } public void reset() { value = 0; update(); } public void connectTo( Message msg ) { message = msg; update(); } }

14 Generalization Look for conceptual commonalities in the abstractions:
common attributes e.g., all vehicles have ? common actions e.g., all vehicles can ? The Outline

15 Example Designing a Class Hierarchy

16 Designing a Class Hierarchy

17 Generalization Java interface:
set of methods that is implemented by classes satisfying the interface this interface is common to the implementing classes this interface represents a “capability” common to the implementing classes but only generalizes about method signatures

18 Generalization Inheritance:
generalize about method signatures, method implementations, and data a base class (or superclass) defines the shared interface and implementation a derived class (or subclass) is endowed with the interface and implementation of its base class

19 Specialization Inheritance:
“is a” relationship between abstractions or classes e.g., a bus “is a” land-based vehicle a derived class can extend the base class by adding new data and methods

20 Why Inheritance? Programming: Design: Software engineering:
factor out repetitious, reusable code Design: application domain modeling Software engineering: make systems flexible and extensible Blah

21 Sharing Implementation
public class Number { private int value; private TextBox textBox; public Number( int initValue ) { … } public Number() { … } public void showIn( TextBox tbox ) { … } public void show() { … } public void next() { … } public void reset() { … } public int value() { … } }

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

23 Sharing Implementation
Commonalities: data value textBox methods showIn( … ) show() reset() value() Differences: data base methods constructors next()

24 Sharing Implementation

25 Sharing Implementation
Cycler “is a” DisplayableNumber a Cycler object can be used wherever a DisplayableNumber object can be used a Cycler object responds to the same calls (messages) as a DisplayableNumber object DisplayableNumber number = new Cycler();

26 Inheriting Methods and Data
public class DisplayableNumber { // version private TextBox textBox; protected int value; public DisplayableNumber( int initValue ) { … } public void showIn( TextBox tbox ) { … } public void show() { … } public void reset() { … } public int value() { … } }

27 Inheriting Methods and Data
public class Number extends DisplayableNumber { public Number( int initValue ) { … } public Number() { … } public void next() { value++; } } public class Cycler extends DisplayableNumber { private int base; public Cycler( int base, int initValue ) { … } public Cycler( int base ) { … } public Cycler() { … } public void next() { … } }

28 Inheriting Methods and Data
public class DisplayableNumber { // version private TextBox textBox; private int value; public DisplayableNumber( int initValue ) { … } public void showIn( TextBox tbox ) { … } public void show() { … } public void reset() { … } public int value() { … } protected void setValue( int v ) { value = v; } protected int getValue( return value; } }

29 Inheritance Java has only single inheritance.
Inheritance hierarchy is a tree. Root class is java.lang.Object. Final classes cannot be extended. Mixin classes.

30 Constructors Constructors are called bottom-up but executed top-down.

31 Constructors public class Number extends DisplayableNumber { … public Number( int initValue ) { super( initValue ); // explicit call to super( … ); // must be first statement in constructor; // superclass data is initialized } … } public class DisplayableNumber { … public DisplayableNumber( int initValue ) { // implicitly inserted call to super(); value = initValue; } … } The Outline

32 Default Constructor If Number does not define a constructor, Java implicitly inserts: // default constructor // Number inherits from DisplayableNumber public Number() { super(); } However, if DisplayableNumber does not have the required: // no-argument constructor public DisplayableNumber() { … } Compilation error. Blah

33 Shadowing Data public class DisplayableNumber { protected int value; // 2, … } public class Number extends DisplayableNumber { private int value; // 0, … public void test() { value = 0; this.value = 1; super.value = 2; ((DisplayableNumber)this).value = 3; // two “value”s in the Number object } }

34 Replacing Inherited Methods
A subclass can redefine an inherited method by overriding it. The overriding method has the same signature. Overriding != overloading.

35 Replacing Inherited Methods

36 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; } }

37 Extending Inherited Methods
To extend an inherited method, override it, and also call it (to do part of the work).

38 Extending Inherited Methods
public class Cycler extends DisplayableNumber { private int base; … public void reset() { // call overridden method; // does not need to be first statement super.reset(); value = value % base; } }

39 Hiding Inherited Methods
To prevent an inappropriate superclass method from appearing in a subclass, hide it by: overriding the method, or using aggregation, or revising the inheritance hierarchy

40 Hiding Inherited Methods
Too much hiding probably means a violation of the “is a” relationship between the superclass and subclass.

41 Hiding Inherited Methods
Suppose: class Dog has bark(), fetch() class Cat inherits from Dog, but hides bark(), fetch(), and adds purr() Cat “is a” Dog?

42 Hiding Inherited Methods
Suppose: class Window has show(), hide(), move(), resize() class FixedSizeWindow inherits from Window but hides resize() FixedSizeWindow “is a” Window?

43 Hiding Inherited Methods
Suppose: class Vector has addElement(), insertElementAt(), elementAt(), removeElementAt(), … class ProjectTeam inherits from Vector ProjectTeam “is a” Vector?

44 Hiding Inherited Methods
public class Rectangle { … public Rectangle( Shape s ) { … } public void setLocation( Location p ) { … } public void setShape( Shape s ) { … } public void draw() { … } public void clear() { … } public void rotate() { … } … } public class Square extends Rectangle { // want to hide setShape() } Square “is a” Rectangle?

45 Overriding the Method public class Square extends Rectangle { … public void setShape( Shape s ) { // should not implement } … }

46 Using Aggregation public class Square { private Rectangle rect; public Square( int side ) { rect = new Rectangle( new Shape( side, side ) ); } public void setSide( int newSide ) { rect.setShape( new Shape( newSide, newSide ) ); } … // Square “has a” Rectangle }

47 Revising the Inheritance Hierarchy
public class Quadrilateral { … public Quadrilateral( Shape s ) { … } public void setLocation( Location p ) { … } public void draw() { … } public void clear() { … } public void rotate() { … } } public class Rectangle extends Quadrilateral { public Rectangle( Shape s ) { … } public void setShape( Shape s ) { … } } public class Square extends Quadrilateral { public Square( int side ) { … } public void setSide( int side ) { … } }

48 Dynamic Binding Binding refers to how a method is selected to be run.
In static binding, the selection is known and made at compile time. In dynamic binding, the selection is made at run time, depending on the type of the object.

49 Dynamic Binding public class Base { // default implementation public void op() { … } } public class Derived1 extends Base { … // does not override op() } public class Derived2 extends Base { // override public void op() { … } } 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

50 Dynamic Binding The object does the right thing, even if the calling code does not know its type. Interrelated concepts: inheritance, type casting, method overriding, abstract methods. Polymorphism.

51 Overriding is not Shadowing
class A { int i = 1; int f() { return i; } } class B extends A { int i = 2; // shadow int f() { return -i; } // override } public class Test { public static void main( String args[] ) { B b = new B(); // b.i is // b.f() returns A a = (A)b; // a.i is // a.f() returns -2, “dynamic binding” } }

52 Abstract Methods The base class method to be overridden can be:
a method with a default implementation a method with an empty body an abstract method (no implementation, subclass responsibility to implement)

53 Abstract Classes A class which is explicitly designed to be the superclass for a set of dependent classes, but which does not itself provide sufficient functionality for independent use, is known as an abstract base class (ABC). A method in a ABC which must be overridden in each descendent class (and will fault if not) is known as an abstract method

54 Example: Abstract class
abstract class Shape { Color color; int x,y; void setColor(Color newColor) { color = newColor; draw(); } void setXY(int xCoord, int yCoord) { x = xCoord; y = yCoord; abstract void draw(); }

55 Example: Shape Comments
No instances of Shape can be created Two methods with default implementations One abstract method All subclasses of Shape must override draw There can be variables of class Shape; at run time they will be constructed as instances of a particular subclass of Shape

56 why abstract classes? All Shape subclasses exhibit the same behavior
This behavior is specified at the abstract class level, and then all shapes are manipulated as Shapes except from their construction When constructed, each shape will be of a particular subtype of Shape At run time, when a particular behavior is required of a particular object, this behavior will be implemented polymorphically depending on the actual class of the object

57 Designing a Class Hierarchy
Need to have a logical, rational explanation for the organization of the hierarchy.

58 Designing a Class Hierarchy

59 Designing a Class Hierarchy

60 Designing a Class Hierarchy

61 Designing a Class Hierarchy

62 Designing a Class Hierarchy

63 End What did I learn today? What questions do I still have?


Download ppt "CMPUT 301: Lecture 06 Interfaces, Abstract classes and Inheritance"

Similar presentations


Ads by Google