telecooperation/rbg technische universität darmstadt copyrighted material; for tud student use only...
TRANSCRIPT
Telecooperation/RBG
Technische Universität Darmstadt
Copyrighted material; for TUD student use only
Introduction to Computer Science ITopic 13: Inheritance, templates and
late binding of methods
Prof. Dr. Max MühlhäuserDr. Guido Rößling
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
• Inheritance: Motivation• Incremental programming• Definition of new object types in Java• Basics of the package acm.graphics• Modeling a graphical system• Abstract classes• Interfaces• Overriding existing definitions• Late binding of method implementations at
method invocation
Contents
2
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Inheritance: Motivation
• In T12, we have defined a concept hierarchy– Client and Employee are special instances of Personen
• Manager and Housemanager are again special instances of Employee
– OneFamilyHouse and MultiFamilyResidence are special Houses
• The general terms (House, Person) have characteristics that also belong to their more specific sub-terms– Person: for example name, first name, phone number, …
• Employee: office– House: address, price, state, …
• We want to use the same concept in Java– Attributes as those above should not be defined multiple
times– Shared methods should be implemented only once
• setName(String), setGivenName(String), setPhoneNumber(String),…
3
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Motivation for new Object Types
• The class Person represents general (abstract) persons
• In the context of real estates, we can only work with concrete persons who have a certain function– For example, they can be a Manager, HouseManager or
Client• However, we do not always want to state which type
of person we expect– Method getPhoneNumber(Person p) does not depend on
the concrete type of person– We do not want to re-implement this method multiple times– In this case, „all sorts of Person “ should match type
Person!• At the same time, the subtypes have special
methods– getListOfManagedClients() vs. getListOfHouses() etc.
4
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Bringing it all Together
• Employee, Manager, Client, … are each classes– This allows us to realize the different functionality cleanly– However, they should “fit Person” as needed (
getName())• Shared methods should be implemented only once
– Avoid redundant code– Reduces the number of possible error sources– Improves the maintainance and reuse
• Java has a concept for this: Inheritance– We say “class Employee inherits from class Person”
• Or shorter: Employee inherits from Person
5
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Basic Inheritance Rules I
• Rule 1: Inheritance describes a specialization– The subclass is a specialized form of its ancestor
• A Client is a special type of Person– Conversely, the ancestor is a generalization of its
subclasses• A Person is a generalization for Client, Employee, …
• Rule 2: Inheritance describes a „is-a“ relationship– A Client is a (special type of) Person– A MultiFamilyResidence is a (special type of) House
• Inheritance does not describe a „has-a“ relationship!– A Client has a (owns, one or more) House– But a Client is not a House– We use attributes for has a: class Client has a list of
houses as an attribute 6
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Basic Inheritance Rules II
• Rule 3: A class inherits all methods and attributes of its ancestor– The class can add more methods or attributes
• For example, an Employee also has an office number that Person lacks
• Rule 4: Inherited methods may be redefined– The implementation of the method will be overridden– More about this later in this slide set…
• Rule 5: The general behavior of the subclass in a given inherited method should fit the one of the ancestor– We cannot “undefine” unwanted methods– We should also not “adapt” them by overriding with an
empty body• Example: Client always returns null in method getGivenName()• May to problems when we want to ask a Person for the given
name
7
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Our Goal: New Object Types
• In the following, we will consider new object types• Definition of new types of objects• Creating and using new instances (objects) of these
types• Specification of general types without direct
functionality• Adaptation of inherited methods by overriding
8
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Motivation for New Object Types• Motivation / advantages:
– More complex actions per instruction– The units we work with become closer to the natural
language– Easier to understand and – if necessary – to correct
9
Mental Model Design Model
module structure of programMachine Level
low abstractionmismatch
low representationalgap
compiler
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
• Inheritance: Motivation• Incremental programming• Definition of new object types in Java• Basics of the package acm.graphics• Modeling a graphical system• Abstract classes• Interfaces• Overriding existing definitions• Late binding of method implementations at
method invocation
Contents
10
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Defining new object types
• We will define new types incrementally– By their difference to existing types Specialization
from more general concepts• A manager is a special kind of employee
• We will also learn to generalize commonalities of different types into a common super-type– Super-ordinate / Subordinate concepts
• rectangles and triangles are both subordinate concepts of graphical objects (all can be drawn on a medium, e.g.,)
11
Construct a new program component N by specifying the difference to an existing
component B, without modifying B.
Construct a new program component N by specifying the difference to an existing
component B, without modifying B.
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Incremental programming by analogy
12
Imagine you have the slide B (Base) on a projector and want to construct the figure on slide N (New) out of B without destroying B. You could put M (Modification) on top of B.
Overlapping slides
B
M
NAt the end, there is B as
well as there is N.Through putting on M, B
is only modified „virtually“ (not physically).
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Incremental programming by analogy
13
B
MN
Advantages• Minimization of work / costs:
• Only the difference is drawn again. The figure on slide B is reused.
• Mistake prevention: B has already been defined and tested. There could be new mistakes when re-drawing it.
• We expect the same advantages when using incremental programming in software construction:– Software is expensive. Repeated development
is unaffordable nowadays.– Reusability of existing assets whenever
possible is an important topic in the software industry.
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Language support for incremental programming• Necessary language constructs: Definition of
new classes as heirs of existing classes by means of inheritance the really new concept of OOP– Definition of new methods / attributes– Overriding of inherited behavior
14
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
• Inheritance: Motivation• Incremental programming• Definition of new object types in Java• Basics of the package acm.graphics• Modeling a graphical system• Abstract classes• Interfaces• Overriding existing definitions• Late binding of method implementations at
method invocation
Contents
15
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Definition of new types in Java: Person
16
public class Person extends Object { String name; String givenName; String address; String phoneNr; // Konstruktor for Person objects public Person(String pName, String pGivenName, String pAddress, String pPhone) { name = pName; givenName = pGivenName; address = pAddress; phoneNr = pPhoneNr; } public String getName() { // returns the Person‘s name return name; } // Methods getGivenName(), setName(String) etc. }
Keyword for inheritance
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Definition of new types in Java
17
The new class „inherits“ all methods and attributes of the base class and may define new ones.
class <Subclass> extends <BaseClass> { [List of new atributes] [List of constructors] [List of new methods]}
class Client extends Person { // ...}
A Client is at first a Person. It has all the attributes and offers all services of a Person.
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Definition of new object types
18
public class Client extends Person { House house; // only one house for now... public Client(String name, String givenName,
String address, String phone, House house) {setName(name);setGivenName(givenName);
setAddress(address); setPhoneNumber(phone); this.house = house; }}
We can use existing services for the definition, e.g. setPhoneNumber(String)
this represents the current object in Java. When it is obvious a method call goes to this, we can also skip this.Other OO have similar special names; for example, Smalltalk uses self.„this.house“ is the attribute of the object, not the parameter of the constructor.
Preliminaryversion
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Excursion: Naming New Methods
• Naming and correctness of new methods– Java does not understand the method name– The following method is thus correct, but not
what we would expect—it will confuse users!public void getMyName() {System.err.println(myHouse);
} • This method should rather be called
„printHouseInfo()“ – Result: intention errors in program—the program
will not react as anticipated.
• Name methods according to their contents!
19
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Constructors and New Types
20
• Subclasses have to call a constructor of its ancestor• A subclass that does not define any constructor receives an
implicit parameterless constructor, which will call the parameterless constructor of its ancestor.
public class Employee extends Person { // Implementation without explicit constructor}
public class Employee extends Person { Employee() { super(); } // ...}
This only works if the ancestor actually defines a parameterless constructor – else we get a compile error (will happen here…)
Keyword for access to elements of the ancestor, here: constructor
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Constructors and New Types
21
• Person only defines a constructor with 4 parameters• Note: As opposed to methods, constructs are not inherited! • Thus, Employee needs to implement an explicit constructor that
will call the constructor with four parameters defined in class Person.
public class Employee extends Person { int officeNumber; // office number public Employee(String name, String givenName, String address, String phone, int officeNr) { super(name, givenName, address, phone); setOfficeNumber(officeNr); } // more features...}
// Example: creating a new Employee
Employee mueller = new Employee("Mueller", "Tim", "Hauptstr. 10, 64289 Darmstadt", "06151-1234567", 10);
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
[Aside: What’s a modeling language?]
22
Mental Model Design Model
module structure of programMachine Level
low abstractionmismatch
low representationalgap
compiler
• Graphical notation (language) in which we write design models.
• More abstract than a programming language. • In general, not executable. • One can generate some code out of a model; supported
by tools.
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Unified Modeling Language (UML)• Language and notation for a visual description of the
design of software systems– Specification how the software system should be constructed– Visualization which can easily be understood even by non
computer scientists– Documentation of software– Particularly important for the design of large systems in a team
• UML provides a collection of diagram types to describe certain aspects of the software– Use-case diagram: What can be done by which actor in the
system?– Class diagram: Describes the relations between classes– Behavioral diagrams: How does the system act?– Implementation diagrams: Components and their relationships
• In the following, we concentrate on the class diagram!
23
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Class diagram in UML
24
UML notationfor method implementations
getOfficeNr() : intsetOfficeNr() : void
return officeNr;
getSupervisedList(): …
UML notationfor inherits
UML notationfor class name : String
…setName(String): void...
Person
Employee
Manager
Note that the inheritance is a transitive relation: Manager inherits everything that Employee also inherits (e.g., setName(String))
Class diagram:• Class properties
• Attributes• Methods
• Relationships:• Inheritance• (Part-of)•
(Dependencies)
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
• Inheritance: Motivation• Incremental programming• Definition of new object types in Java• Basics of the package acm.graphics• Modeling a graphical system• Abstract classes• Interfaces• Overriding existing definitions• Late binding of method implementations at
method invocation
Contents
25
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Modeling a Graphical System
• We now leave our real estate example– While „useful“ for OO modeling, it is not very inspiring
• Instead, we will model a graphical system– This contains a drawing area and graphical objects
• Lines, rectangles, ovals, polygons, …
• For this purpose, we return to the ACM JTF package– See slide set T11, „GraphicsProgram“
• We will base our model on ACM JTF– But we will take time to find a good model of our own– This may not be identical to ACM JTF
• But nobody ever said, that the ACM JTF package were perfect…
26
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Using ACM JTF Graphics
• ACM JTF offers more than Console, Dialog and Graphics– An (almost) complete system for drawing objects on the
screen!• Objects are drawn in the order they are declared:
• The base for this is the well-known „GraphicsProgram“
• We will use additional classes for graphical objects– Arcs, texts, lines, ovals, rectangles, polygons
27
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Basic Concepts for Graphics with ACM JTF
• To create graphics with ACM JTF, you should know…:– The same output window is used as for „HelloGraphics“– The coordinate system starts at the top left with (0, 0)
• The x axis extends to the right, the y axis to below• Each coordinate refers to a single pixel• Both int and double can be used for coordinates
• Basic classes for creating graphics– Class GCanvas represents the drawing area– Class GObject is the ancestor for all graphical objects– To draw, add a GObject subclass to the GCanvas
• Use method add(GObject) in class GCanvas for this• This method is also directly available in GraphicsProgram
• Let us first take a look at the graphical objects…28
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Graphical Objects: Class GObject
• GObject is the base class for all graphical objects– Just as Person was the base class for Employee, Client (T12)
• Most relevant methods:– double getX(), double getY(), GPoint getLocation()
• Returns the x / y coordinate of the object or its location as a point
– void setLocation(double x, double y),void setLocation(GPoint p)
• Sets the coordinate of the object to (x, y) or to the point passed in
– double getWidth(), double getHeight()• Returns the width or height of the object
– GDimension getSize()• Returns the size of the object as an instance of GDimension
– GRectangle getBoundingBox()• Returns the smallest rectangle that completely covers the object29
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Graphical Objects: Class GObject
• Moving an object:– void move(double dx, double dy),void setLocation(GPoint p)
• Moves the object by (dx, dy) or sets it to the location p• Internally calls setLocation(getX() + dx, getY() + dy)
– void movePolar(double r, double theta)• Moves the object for r units in the direction theta (angular
degrees)
• Retrieving or setting the color of an object:– void setColor(Color c), Color getColor()
• See the Java documentation of java.awt.Color• Usually, the following predefined constant colors should
suffice:– Color.BLACK, Color.RED, Color.BLUE, Color.DARK_GRAY,
Color.YELLOW, Color.MAGENTA, Color.GRAY, Color.GREEN, Color.ORANGE, Color.LIGHT_GRAY, Color.CYAN, Color.PINK, Color.WHITE
• You have to „import java.awt.Color;“ at the start of the class!
30
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Graphical Objects: Class GObject
• Changing the order of drawing– Normally, “newer” objects will be drawn on the front– To change this, use these four methods:
• void sendToFront(), void sendToBack()– Sends the object to the front or back
• void sendForward(), void sendBackward()– Raises or lowers the object by one layer
• Testing whether a given point is contained in the object– boolean contains(double x, double y)boolean contains(GPoint p)• Returns true if the point is inside the object, else false
31
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Display Area: GCanvas
• GraphicsProgram already contains a GCanvas• Most relevant methods in both classes:
– void add(GObject go)• Adds object go to the GCanvas at the position given in go
– void add(GObject go, double x, double y)void add(GObject go, GPoint p)
• Adds object go to the GCanvas at the position passed in– void remove(GObject go)
• Removes the object go from the GCanvas– void removeAll()
• Removes all graphical objects from the GCanvas– int getWidth(), int getHeight()
• Returns the width or height of the GCanvas
32
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Display Area: GCanvas
• void setBackground(Color bgColor)– Sets the background color to bgColor
• GObject getElementAt(double x, double y)GObject getElementAt(GPoint p)– Returns the uppermost object that contains coordinate (x, y)
or p– Calls contains(x, y) or contains(p) on all objects
• Example (T11, Slide 20): // Create a new object: GLabel for texts
GLabel label = new GLabel("hello, world"); // neuw Text // Assign font label.setFont("SansSerif-100"); // Font: no serifs
// determine position and add to the canvas double x = (getWidth() - label.getWidth()) / 2; // centered double y = (getHeight() + label.getAscent()) / 2; // centered add(label, x, y); // add text to the GCanvas
33
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Example: two objects on the Canvasimport java.awt.Color; // for colorimport acm.graphics.GOval; // for the ovalimport acm.graphics.GRect; // for the rectangleimport acm.program.GraphicsProgram; // our ancestor
public class FeltBoard extends GraphicsProgram { public void run() {/** Runs the program */
GRect rect = new GRect(100, 50, 100, 100 / PHI); // def. rect rect.setFilled(true); // rectangle is filled... rect.setColor(Color.RED); // ...with red add(rect); // add to GCanvas
GOval oval = new GOval(150, 50 + 50 / PHI, 100, 100 / PHI); oval.setFilled(true); // also filled... oval.setColor(Color.GREEN); // but green add(oval); // add to GCanvas
}
34
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Example: two objects on the GCanvas/** Constant representing the golden ratio */public static final double PHI = 1.618;
/* Standard Java entry point *//* This method can be eliminated in most Java environments */public static void main(String[] args) {
new FeltBoard().start(args);}
}
Output (see slide 27):As the rectangle as added first,it is places behind the ovalthat was added later.
35
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Predefined subclasses of GObject
• GLine: Line between two points– GLine(double x1, double y1, double x2, double y2)
• Creates a line from (x1, y1) to (x2, y2)– GPoint getStartPoint()GPoint getEndPoint()
• Returns the starting or ending point of the line
• GOval: oval shape– GOval(double x, double y, double w, double h)
• Creates an oval with upepr left corner (x, y) and radius w and h
• GLabel: Text– GLabel(String text, double x, double y)
• Text „text“, starting at (x, y) with baseline y
36
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Predefined Subclasses of GObject• GArc: Arc; like GOval, but with start and end angle
– GArc(double x, double y, double w, double h, double start, double sweep)
• Arc with left upper corner of ist bounding box at (x, y), radius w and h, start angle start and total angle sweep (measured in degrees)
– Several further methods for getting or setting arcs angles• GPolygon: Polygon with an arbitrary number of points
– GPolygon(double x, double y)• Creates a polygon at (x, y) without any additional points
– GPolygon(GPoint[] points)• Creates a polygon with the nodes given in the array
– addEdge(double x, double y)• Adds a new edge from the last known point to (x, y)
– void markAsComplete()• Mark polygon as “complete”; no further addition is possible
37
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Predefined Subclasses of GObject
• GRect: rectangle in three variant forms– GRect(double x, double y, double w, double h)
• Creates a rectangle with nodex (x,y) and (x+w, y+h)– G3DRect(double x, double y, double w, double h)
• Creates a rectangle with a “3D effect”• Additional parameter: boolean raised; if true, draws “raised”
– GRoundRect(double x, double y, double w, double h)• Creates a rectangle with rounded edges• Additional parameters:
– double arcSize – size of the edge angle– double arcWidth, double arcHeight – individual sizes
• GImage: allow inclusion of images– GImage(Image image, double x, double y)
• Creates an image; not regarded for now
38
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Aside: Drawing GObject Instances
• The drawing of GObject instances is done internally– In the method void paint(Graphics g), defined in class GObject– Graphics is a rather powerful class from java.awt
• Please consul the Java API Dokumentation for details!
• Drawing a rectangle (slightly simplified) using Graphics:public void paint(Graphics g) {// draw rectangle from (x, y) with width and heightg.drawRect(getX(), getY(), getWidth(),getHeight());
}
• Drawing a square (slightly simplified) using Graphics:public void paint(Graphics g) {// draw square from (x, y) with fitting sizeg.drawRect(getX(), getY(), size, size);
}
39
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
• Inheritance: Motivation• Incremental programming• Definition of new object types in Java• Basics of the package acm.graphics• Modeling a graphical system• Abstract classes• Interfaces• Overriding existing definitions• Late binding of method implementations at
method invocation
Contents
40
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Determining the „best“ Inheritance Hierarchy
• The choice of the „best fitting“ modeling is not always obvious
• We will now regard the following classes as parts of a graphical system:– Point (GPoint)– Rectangle (GRect)– As needed, also a class for squares (GSquare)
• We will examine different modeling approaches– We will also argue why a given modeling is (not)
„appropriate“.
41
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Model I: Point as Ancestor
• Idea: „all graphical objects consist of at least one point“
• Inheritance Rule 1: „subclass is a specialization“– Is a „rectangle a specialized point“?
• What we meant was: a rectangle contains at least one point– We should use a GPoint as an attribute, not as the
ancestor!– See Inheritance Rule 2: „is-a“ vs. „has-a“ 42
GPoint
GRect
This is a bad
choice!
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Model II: Point next to Rectangle
• GPoint should not be the base class for a rectangle– The same reason applies to other graphical objects
• We now define a general base class „GObject“– This will not represent a concrete object
• Concrete methods such as paint will be left empty in GObject
– The class gathers common functionality of all graphical objects
– Concrete tasks, such as painting, have to be done by subclasses
43
GObject
GPoint GRect
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Model III: Rectangle and Square
• How should we model the rectangle and square?– A square is more special than a rectangle– Thus, we could use rectangle as the base class for square
44
GSquare
GObject
GPoint GRect
Is this really a good model?
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Model III: Rectangle as Ancestor of Square
• Attention: Inheritance Rules 3 and 5– 3: „A class inherits all methods and attributes of its ancestor“– 5: „The general behavior of the subclass in a given inherited method
should fit the one of the ancestor“• Square thus inherits all attributes and methods from Rectangle
• Thus, also the two points upper left, lower right• And methods such as setWidth(double), setHeight(double)• How can we ensure that the shape stays a square?
• How can we adapt the method for changing the size?– Rectangle: two values or a Gdimension object– Square: one value– The inherited methods from Rectangle must stay available– We can at best “override” them:
public void setSize(double w, double h) {setSize((w + h) / 2);
}
• This does not match the behavior of the ancestor Rule 545
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Model IV: Square as Base Class for Rectangle
• What happens if we change the order: Rectangle inherits from Square?– Rectangle inherits a size and „adds a second size“void setSize(double size) { setSize(size, size);}– This is possible and does not violate Inheritance Rule 3+5– But: a rectangle is a generalization of a square, not a
specialization!• Thus, this model is also not a good choice• We will add GSquare next to GPoint, GRect
46
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Using new Object Types
• We extend our class FeltBoard (slide 34-35): // Code until end of method "run" as before
add(oval); // add to GCanvas
// update: a new object is introducedGSquare square = new GSquare(120, 80, 60);square.setColor(Color.BLACK);add(square);// continue as before...
47
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
• Inheritance: Motivation• Incremental programming• Definition of new object types in Java• Basics of the package acm.graphics• Modeling a graphical system• Abstract classes• Interfaces• Overriding existing definitions• Late binding of method implementations at
method invocation
Contents
48
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Templates & Abstract Classes• Let us examine the class GObject more closely…• Classes GPoint, GRect and GSquare inherit from
GObject• This also includes the method void paint(Graphics g)
– How can this method be implemented for a general GObject?– We do not even know what type of object it is supposed to be!
• For this purpose, classes may declare methods which are not implemented inside the class.– Such methods are called abstract methods.– Classes which contain at least one abstract method
are called abstract classes.
• We will now examine how abstract classes support reuse if similar, but not identical tasks have to be implemented.
49
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Abstract Classes: GObject• GObject represents arbitrary graphical object
– Thus, nothing concrete such as a circle, square – only a template
• GObject provides general functionality to all subclasses– Setting and getting the coordinate and color– Determining the bounds of the object (bounds)– Drawing the object using paint(Graphics)
• Not all methods can be implemented– How can we draw a “template”? As a circle, square, …?– How can we determine the bounds of a template?
• How do we treat this situation?– What do we want to achieve?
• Each concrete subclass must implement these two methods• This should be ensured by Java, not only by (potentially ignored)
comments in the source code and documentation
50
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Treatment of non-concrete Methods
• Approach 1: we leave those methods empty in GObjectpublic void paint(Graphics g) { }– The method is implemented, but has no functionality– Subclasses should implement paint, but Java does not
enforce that• Approach 2: we implement those methods
„somehow“– E. g., an error message is printed, “so that the user sees the
call was incorrect“– Classes compile normally, end user sees the errors
• Unless the console was minimized…– The program may behave incorrectly
• Depending on the implementation of getBounds(), getElementsAt() may return the wrong objects
51
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Abstract Methods and Classes in Java
• A „non-concrete“ method is called abstract• Marked in Java by abstract before the return type• Abstract methods are only declared
– Instead of the curly braces, there is only a semicolon ;public abstract void paint(Graphics g);
• A class with at least one abstract method must also be declared abstractpublic abstract class GObject { ... }
• As an abstract class is incomplete, no object of this type can be createdGObject go = new GObject(); // Error!
52
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Abstract Classes and their Descendants
• A class that inherits from an abstract class…– Inherits the declarations of all abstract methods– Can implement abstract methods
• See getBounds() and paint(Graphics) in GSquare
• Unless all abstract methods are implemented, the descendant is also abstract– This is true even if the inherited method does not show up
explicitly as „abstract“ in the class source code, for example because we have left out „getBounds()“ in GSquare
• Only the conkrete implementation of all abstract methods results in a completely implemented class…– …of which we can then create actual instances using new
53
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Using Abstract Classes
54
// ... public void run() { // s. Folie 35 und 36 GRect rect = new GRect(100, 50, 100, 100 / PHI); rect.setFilled(true); rect.setColor(Color.RED); add(rect); GOval oval = new GOval(150, 50 + 50/PHI, 100, 100/PHI); oval.setFilled(true); oval.setColor(Color.GREEN); add(oval);}// ...
• Let us return to the code on slide 34f:
• The highlighted method setColor was inherited without changing it from GObject
• The method add calls (invisibly) the paint(Graphics)
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Abstract Classes• Shared aspects in the super class GObject
– Method contains(double, double) tests, if a given point is contained in the object; uses getBounds()
– However, getBounds() is abstract
55
abstract class GObject extends Object{ //Konstruktor (versteckt)
boolean contains(double x, double y){ return getBounds().contains(x, y);
} abstract GRectangle getBounds();}
Unimplemented Operation. It is only declared here; means “all concrete GObject instances offer the service getBounds()“. However, we cannot provide a shared implementation of this.
Template method.Calls primitive abstract operations.
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Descendants of Abstract Classes
56
class GRect extends GObject{ double frameWidth, frameHeight; // Konstruktor etc... GRectangle getBounds() { return new GRectangle(getX(), getY(), frameWidth + 1, frameHeight + 1); }}
class GSquare extends GObject{ double frameSize; // Konstruktor etc... GRectangle getBounds() { return new GRectangle(getX(), getY(), frameSize + 1, frameSize + 1); }}
Grect and GSquare implement the template differently
Use width and height for the result
Use the size (both times) for the result
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Abstract Classes in UML
57
GRectgetBounds(): GRectangle
GSquaregetBounds(): GRectangle
UML notation for
abstract classes
UML notation for
abstract methods
GObject
contains(double, double): booleangetBounds(): GRectangle
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Model V: Decoupling the classes
• Similarly to GPoint and GRect, we can decouple GRect and GSquare
58
GSquare
GObject
GPoint GRect
• This works without any problem• But the common aspects of GRect and GSquare are
gone• For example, both might be filled and have a fill
color• However, a GPoint does not have this
functionality.
Is this really a good model?
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Implementation of GSquare
• What do we have to do when implementing GSquare?– The method drawRect expects four parameters of type int
• Round the double coordinates and convert to int– We have to specify constructors for GSquare
• Otherwise, we cannot create a new instance of GSquare!• We will define two constructors:
– Specification of only the size—the start coordinate will be (0, 0)– Specification of size and starting point
• Solving most of these problems is easy– See the next two slides for the code!
59
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Complete Code for GSquarepackage acm.graphics; // Belongs to package acm.graphics
import java.awt.Graphics; // needed for paint(Graphics)
public class GSquare extends GObject { // derived from GObject private double frameSize; // size of the square
public GSquare(double size) { // Create without coord.-> (0, 0)
this(0, 0, size); // Call other constructor }
public GSquare(double x, double y, double size) {frameeSize = size; // Store size of squaresetLocation(x, y); // set the location (->GObject)
}
public double getSquareSize() { // return size of squarereturn frameSize; // return internal size
}60
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Complete Code for GSquare
public GRectangle getBounds() { // determine box return new GRectangle(getX(), getY(), frameSize+1, frameSize + 1);
}
public void paint(Graphics g) { // draw it! g.drawRect((int)GMath.round(getX()), (int)Math.round(getY()),
(int)Math.round(frameSize), (int)Math.round(frameSize));
}}• Similarly, we could define additional types such as GTriangle
61
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
• Inheritance: Motivation• Incremental programming• Definition of new object types in Java• Basics of the package acm.graphics• Modeling a graphical system• Abstract classes• Interfaces• Overriding existing definitions• Late binding of method implementations at
method invocation
Contents
62
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Model VI: Abstract Class GFillableObject
• We can define an abstract class for filled objects, for example with the following attributes and methods:– boolean isFilled– Color fillColor– boolean isFilled(), void setFilled(boolean filled)– Color getFillColor(), void setFillColor(Color c)
• All methods can be implemented and inherited
63
GSquare
GFillableObjectGPoint
GRect
GObject
Is this really a good model?
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Model VI: Abstract Class GFillableObject
• This is basically a clean and working structure• But now, all filled structures must be derived of
class GFilledObject or one of its subclasses• We can no longer provide a good model for a class
…– … that has a fill color and may be filled– … allows setting and retrieving the fill color and fill state– … therefore acts like a descendant of GFilledObject …– … but does not extend GFilledObject
• For example, because it specializes some other type
• We block the road for future classes!– We need a concept to “evade” the single inheritance of
Java– Even if this may result in some code redundancy.
64
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Interfaces
• Interfaces declare methods (services), without implementing them– An interface type contains only method signatures:
return type, name, list of parameters and their types• Functional Abstraction: the what but not the
how– Separation of declaration and implementation
65
+operation(): void
<<interface>> AnInterface
UML Notation Java syntax
interface AnInterface {
public void operation();
}
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Implementing an Interface• A class implementing an interface…
– Either has to implement all methods declared in the interface, or it must be declared abstract• Implemented methods retain their
signature and must be public– The class can also define additional
methods
• Multiple Java classes can implement the same interface in different ways.
• In Java, a class can implement multiple interfaces– But it can only inherit from one class!
66
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Implementing an Interface
67
ClientClasscalls
ImplClass1
AnInterface is implemented by ImplClass1 and
ImplClass2 . ImplClass2
<<interface>> AnInterface
<<interface>>AnotherInterface
operation(): void
+operation(): void+operation(): void
UM
L nota
tion
for im
ple
ments
class ImplClass1 implements AnInterface {
public void operation () { // ... }}
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Interface Inheritance
• An interface can inherit from one or more “super-interfaces” (keyword extends).
• A class AClass implementing interface B has to implement all methods declared in B (including those of the super-interfaces).– Otherwise, AClass remains abstract
68
«interface»A
«interface»B
AClass
operation1()operation2()
operation3()
operation1()operation2()operation3()
interface B extends A {
public void operation3();
}
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Variables of an Interface Type
69
• Similar to class types, we can also declare variables of an interface type
• Remember that you cannot instantiate interface types!
class AnInterfaceClient { AnInterface aVariableName; // ... void someOperation() { aVariableName = new AnInterface(); aVariableName = new ImplClass1(); aVariableName.operation(); }}
A class using interface types for the declaration of some attribute can be reused, as long as the variables contain objects of a class type that implements the interface.
Error
OK
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Interfaces and (abstract) Classes
• Abstract Class define (and implement) common functionality
• Interface declare a common type, but no shared functionality
• A class can only extend one class (single inheritance) abusing abstract classes when an interface would be sufficient has important side-effects!
• Note: Some programming languages allow a class to extend multiple other classes (multiple inheritance).– This often creates naming conflicts, for example if the same
method is inherited from two different super classes.– So far, there is no really satisfying implementation for this
problem.
70
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Interfaces and (abstract) Classes• Single inheritance enforces a single classification scheme on
classes. • Using interfaces relaxes this situation somewhat:
– A GRect can be filled and scaled– A GSquare can be filled but not scaled– A GPoint cannot be filled or scaled
71
interface GFillable { // for fillable objects boolean isFilled(); void setFilled(boolean b); Color getFillColor(); void setFillColor(Color fillColor);} interface GScalable { // for scaling by one or separate factors void scale(double factor); void scale(double scaleX, double scaleY);}class GRect extends GObject implements GFillable, GScalable ...class GSquare extends GObject implements GFillable...class GPoint extends GObject...
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Model VII: Using Interfaces
• We declare an interface GFillable• This interface declares the methods for setting and
getting the fill state and the fill color• Consequence for implementers of GFillable:
– The methods have to be implemented locally redundancy– But we can also freely choose the base class flexibility
72
GSquare
<<interface>> GFillable
GPoint GRect
GObject
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Summary: Modeling
• Choosing the “right” super class may not be obvious• The choice may also depend on our goals and the
context• Several of our models were not recommendable
– Model I: Point as base class for Rectangle• A rectangle is not a point, it only contains (usually two) points
– Model II: Concrete class GObject with empty paint()• Subclasses are not enforced to implement this method!
– Model III: Square extends Rectangle • Some of the inherited attributes and methods are „superfluous“
and may cause problems, for example setWidth(double)– Model IV: Rectangle extends Square
• A rectangle is a generalization, not a specialization, of a square– Model VI: abstract class GFillableObject
• Conceivable, but limits inheritance73
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
• Inheritance: Motivation• Incremental programming• Definition of new object types in Java• Basics of the package acm.graphics• Modeling a graphical system• Abstract classes• Interfaces• Overriding existing definitions• Late binding of method implementations at
method invocation
Contents
74
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Overriding existing definitions
• Method overriding occurs when two methods with the same name, same number of parameters and the same parameter types (=the same signature) are defined in different classes, and one class is the superclass of the other.– Synonym for Shadowing, Hiding
• Why is this useful?– Because the behavior of the inherited types Is close to
what we wanted. – Specialization is not only extension…
• Rectangles and squares inherit the functionality to be painted from a common ancestor, but realize them differently…
75
B
MN
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Overriding existing definitions
76
class GRect extends GObject implements ...{ // Konstruktor etc... void paint(Graphics g) { Rectangle r = getAWTBounds();
if (isFilled()) {g.setColor(getFillColor());g.fillRect(r.x, r.y, r.width,
r.height);g.setColor(getColor());
} g.drawRect(r.x, r.y, r.width, r.height);
}
The method paint in GRect uses the methods getColor(), getFillColor()
class GStrangeRect extends GRect { // Konstruktor etc. Color getFillColor() { setColor(Color.BLUE); // ! return super.getFillColor(); }}
We now implement a “strange rectangle” that redefines some methods
What happens here?
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Overriding existing definitions
77
class GStrangeRect extends GRect { // ... Color getFillColor () { setColor(Color.BLUE);
return super.getFillColor(); }}
• „Old“ methods are no longer visible outside their new definition!
• We can use the implementation we have overriden (e.g., the paint operations for the super class) within the new declaration with super Informally: „call the
version of getFillColor() that is visible in my GRect variant.“
Technically: „execute the first implementation of getFillColor() that you can find along the chain of my ancestors.“
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
• Inheritance: Motivation• Incremental programming• Definition of new object types in Java• Basics of the package acm.graphics• Modeling a graphical system• Abstract classes• Interfaces• Overriding existing definitions• Late binding of method implementations at
method invocation
Contents
78
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
class GStrangeRect extends GRect { // Konstruktor etc. …// Verschiebt sich vor dem Zeichnen void getFillColor() { setColor(Color.BLUE); return super.getFillColor(); }}
Choosing the correct Called Method• When a method OP is called on an object obj of type
ObjType, the correct method has to be chosen and executed („method dispatch“).
• In OO languages, methods names are bound dynamically to methods.
79
Attention! What happens when we call paint(g)?
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
public void run() { // inside FeltBoard (slide 35+) GRect rect = new GRect(100, 50, 100, 100 / PHI); rect.setFilled(true); rect.setColor(Color.RED); add(rect); // indirectly calls paint(g) GStrangeRect rect2 = new GStrangeRect(130,80,100,100/PHI); rect2.setFilled(true); rect2.setColor(Color.RED); add(rect2); // indirectly calls paint(g)}
Choosing the correct Called Method
80
Overriding getFillColor() in GStrangeRect leads to strange behavior of paint() in class GStrangeRect – but why?
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Choosing the correct Called Method
81
rect2Class
Each object knows its own class
First rule: The search for an implementation for a given operation starts in the class of the receiving object and goes up the inheritance hierarchy, until an implementation was found (or, in dynamically typed languages, until the root of the hierarchy was reached)
GRectgetFillColor(): Colorpaint(Graphics): void...
GStrangeRect
getFillColor(): Color
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Calling paint(Graphics)
82
rect
Cla
ss
GRectgetFillColor(): Colorpaint(Graphics): void...
GStrangeRect
getFillColor(): Color
run()
paint(g)
if (isFilled) { g.setColor( getFillColor())...
• Calling rect.paint(g) uses the method paint(g) in GRect• Calling getFillColor() again leads to class GRect
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Calling paint(Graphics)
83
rect2Clas
s
GRectgetFillColor(): Colorpaint(Graphics): void...
GStrangeRect
getFillColor(): Color
run()
paint(g)
if (isFilled) { g.setColor( getFillColor())...
setColor(Color.BLUE);return super.getFillColor();
• Calling rect2.paint(g) looks for paint(g) in GStrangeRect• As the method was not overriden, we use the code found in
GRect• The class of getFillColor() again goes to the object rect2• This will now use the overriden method and change the color• At the end, we will call the method as implemented before
using super
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Overriding inherited methods
84
• Class GStrangeRect overrides the inherited method getFillColor• The method in class GRect remains unchanged
• The method name getFillColor will not be “bound forever” to the code found in class GRect!
• Binding happens dynamically:• For method invocations, Java start with the current dynamic
type of the object to look for the first “fitting” implementation
• Thus, when we call rect2.paint(g)…:• For paint(g), we will use the code of class GRect• For the method called inside paint, we determine the
dynamic type of the object• That type is GStrangeRect (since we work on rect2)
• We now use the first “fitting” method implementation• This again comes from GStrangeRect
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Dynamic Method Binding
85
rect2Class
GRectgetFillColor(): Colorpaint(Graphics): void...
GStrangeRect
getFillColor(): Color
rectClass
run()p
ain
t(g
)Method binding occurs only during the dynamic execution of the program.
It depends on the type of object receiving the message.
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Binding super-Invocations
86
rect2Clas
s
GRectgetFillColor(): Colorpaint(Graphics): void...
GStrangeRect
getFillColor(): Color
run()
paint(g)
if (isFilled) { g.setColor( getFillColor())...
setColor(Color.BLUE);return super.getFillColor();
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Binding of this and super Invocations
87
Second Rule: The search for an implemention of super invocations starts in the super class of the class in which the call is placed.
Invocations using this use late binding (dynamic)Invocations using super use early binding (static)
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science: T13
Summary• Classes can inherit, override and extend the functionality of
other classes– The main new aspect of OOP– Supports incremental programming reusability
• Abstract classes support the definition of functional templates reusability
• Interfaces separate type declarations from implementations• Operation names are bound dynamically to implementation
code– The type of the recipient determines the method choice– This also applies to invocations using this
• Invocations to super are bound statically to the next implementation in the inheritance hierarchy
88