Upload
rosamond-gardner
View
216
Download
1
Embed Size (px)
Citation preview
Object-Oriented DesignObject-Oriented Design
CSC 212
Announcements
This course is speeding up and we are starting new material. Please see me if you feel this is going too fast for you.CSC tutoring hours posted outside Wehle 208
I’m new to Canisius. Feel free to give me feedback about how this class is going. I will always listen and appreciate your adviceCannot guarantee I will follow suggestions
Announcements
If you need additional Java review, seek out help nowHomework #1 will on web tonightWill be due next Thursday (9/22)
Students should use Wehle 208 for their homework If you need, ask me for the access passwords
Questions?
Object-Oriented Design
Goodrich & Tamassia (1st edition), p. 5
Adaptability
How easy is it for the code to evolve?What assumptions are in the design?Are the assumptions stated explicitly?What will happen when the assumptions
become incorrect?How easy is porting the code to a different
environment (portability)?
Robustness
Will the program perform correctly?What assumptions are made about the input?What happens if incorrect input is entered?Can the design expand to handle larger
datasets?Can the program fail gracefully?
Reusability
Can the code be incorporated into other projects?Does it clearly describe what it can do?Does it clearly describe what it can’t do? Is it difficult to understand how to use it? Is it easy to add extra functionality?
Achieving Design Goals
Three principles develop code fulfilling design goalsAbstractionEncapsulationModularity
Abstraction
Distill system to most fundamental parts Important actors should be made into classesEach class describes a single actor/data type
From lab: Rectangle & Vertex should be classes
Designs become adaptable Classes describe important actors more generally Resulting code not specific to problem
Abstraction
Describe design in simple, easy languagePublic methods define actions important to
user Method name active verb describing functionality Enhances reuse – code functionality is obvious
Limiting demands on each method improves robustness
Simplifies testing, also!
Encapsulation
Hide details not needed by userMake implementations methods private
Provides freedom in how code is implemented Improves reuse – easy to understand how to use
class Improves adaptability –change implementation
without needing to change how code is used
Modularity
Organize functional units into separate modulesOrganize separate ideas into separate places
Classes represent only one type of actor Methods perform only one action
Use hierarchical nature of Java to enable sharing of similar code
Hierarchical Nature of Data
Multiple ideas may share actions or dataWant to implement ideas as separate classesBut only one place should contain methods &
fields Java enables this through inheritence
Generic superclass contains shared code & data
Other extend or specialize the superclass
Hierarchical Nature of Data
Example: the Rectangle classWant new class of Rectangle OutlinesBut, cannot change Rectangle class
People are already using previous code May not have access to source code Already tested and documented
Hierarchical Nature of Data
Create RectangleOutline extending Rectangle Add new field (outline) method isOutline()Modify method returning if point is within the
Rectangle A point is within RectangleOutline only if it is on
one of the edges
Rectangle
RectangleOutline
parent classsuper class
child classsubclass
shows “is a” relationship
Data Hierarchies
This relationship could be continued Consider the different rectangles drawn
used for windowsRectangles with Title BarsButtons
Buttons with text Buttons with pictures Buttons with text & pictures
Class Inheritance Diagram
Goodrich & Tamassia (2nd edition), p. 62
Where Does This Go?
Cannot treat classes interchangeablyE.g. Getting picture from TextButton
But sometimes we canAll Rectangles have location and can ask if a
point is inside boundaries Deciding where methods belong is big part
of creating class hierarchy
Class Hierarchy
ButtonRectWithTitle
Rectangleboolean isInternal(Point p)
void move(float offX, float OffY)
String getTitleBarText()
void minimizeWindow()
boolean buttonPushed()
Color getColor()
Inheritance
Classes inherit all fields from its superclass, the superclass’ superclass…
Similarly, classes inherit methods down through the class hierarchy
Organize fields and methods toLimit duplication Make fields & methods useful to ALL subclasses
which inherit them
TextButton
/** * This can represent a button containing text */public class RectWithTitle extends Rectangle { String titleBarText; // If currently an outline
/** Constructor invokes Rectangle() constructor */ public RectangleOutline(Point lowL, Point topR,
String titleBarText) { super(lowL, topR);
this.titleBarText = titleBarText; } …}
1
2
3
Keyword Meanings
1. extends links two classes – the declared class becomes subclass of the other one
2. super enables accessing methods in the superclass; in this case, a Rectangle constructor
3. this specifies access is to member of the current instance.
What Gets Inherited And How?
All public members inherited, stay publicPackage members similarly passed down
Subclass can access protected members as if they were publicEven for instances of the superclass type!
Private members remain in superclass
Polymorphism
Comes from Greek meaning “many forms” Instances of Button can be used like a
Rectangle, since a Button is a RectangleThis is an example of polymorphism
Cannot use Rectangle as Button, howeverCannot use RectangleOutline as Button either
Java’s Object Hierarchy
Class can extend at most one other class If no superclass given, implicitly extend ObjectSo all classes are subclasses of Object
Object defines useful methods, including:public boolean equals(Object obj)protected Object clone() throws
CloneNotSupportedExceptionpublic String toString()
Reusing Names in Classes
Can reuse method names in subclasses Overload method declaration
Subclass defines method with same name, different signatures
Override method declarationSubclass defines method with same name &
signatureSubclass method replaces inherited one
Overloading Methods
Same method name can be used with different data typesConsider how the operator “+” works on int,
float, and Strings Overloading allow subclasses to expand
how an action is defined in superclassBut keeps original methods available, too
Overloading Methods
Overloaded methods differ in argument listsWorks like multiple constructor definitions
Which method executed depends on call parametersE.g., Calls the method which matches the
number, type, and order of argumentsCan methods differ only in return type?
Overriding Methods
Subclass provides new implementation for inherited methodUses same name & signatureWhat return types could be used?
Subclass follows superclass’ throws clause Inherited method cannot use more restrictive
access control
Overriding Methods
When calling method, actual class of instance determines which implementation is executedE.g., Rectangle p1 = new RectangleOutline(…); p1.isInternal(point); // What is called?
Overriding Example
public class SuperClass {
public String getMyString() {return “SUPERSTRING”;}
public SuperClass() { }
}
public class SubClass extends SuperClass {
public String getMyString() {return “substring”;}
public SubClass() { }
public static void main(String[] args) {
SubClass sub = new SubClass();
SuperClass super = sub;
String test1 = sub.getMyString(); // test1 ==
String test2 = super.getMyString(); // test2 ==
super = new SuperClass();
test2 = super.getMyString(); // test2 =
...
Reusing Fields in Subclasses
Subclasses can hide superclass’s fieldsSubclass defines field with identical nameField from superclass also exists in subclass
super.<fieldname> accesses superclass’s field
Which field Java will access? What does this depend on?
Field Hiding Example
public class SuperClass { public SuperClass() { } protected String myString = “SUPERSTRING”; public String getMyString() { return myString; }}
public class SubClass extends SuperClass { public SubClass() { } protected String myString = “substring”; public String getMyString() { return myString; }
Field Hiding Example
public static void main(String[] args) {
SubClass sub = new SubClass();
SuperClass super = subInstance;
String test1, test2;
test1 = sub.getMyString(); // test1 ==
test2 = super.getMyString(); // test2 ==
test1 = sub.myString; // test1 ==
test2 = super.myString; // test2 ==
}
}