object-oriented design csc 212. announcements ask more questions! if i am not making myself clear,...
Post on 19-Dec-2015
216 views
TRANSCRIPT
Object-Oriented DesignObject-Oriented Design
CSC 212
Announcements
Ask more questions! If I am not making myself clear, it is your opportunity to explain what is confusing you (and my chance to try and explain it differently and help solve your confusion)
Get additional Java review nowHomework #1 on web; due in one week
Object Inheritance Review
Subclass represents es can extend or specialize the superclass
Use extends to declare a subclasspublic class subclass extends superclass {...}public class Robin extends Bird {...}public class Van extends Automobile {...}public class ProfHertz extends Genius {...}
Subclass inherits non-private fields and methodsAs if fields & methods were pasted into subclass
code
Object Inheritance Review
Inheritance represents “is a” relationshipE.g., Robin “is a” Bird; Van “is a” Automobile;
Prof. Hertz “is a” GeniusSorry, I couldn’t resist the last example
Subclass can specialize superclassSubclass can add functionalitySubclass can define additional dataSubclass can specialize how instances operate
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; } public String getOldString() { return super.myString; }
Field Hiding Example
public static void main(String[] args) { SubClass sub = new SubClass(); SuperClass supr = sub; System.out.println(sub.getMyString()); System.out.println(supr.getMyString()); System.out.println(sub.myString); System.out.println(supr.myString); System.out.println(sub.getOldString()); }}
Reusing Names Review
Two ways of reusing method names:Overloading – same name, different signatureOverriding – same name, same signatureJava calls the method appropriate to the actual
object instance, NOT the variable type Reusing field name hides inherited field
Both fields exist within the classJava uses field appropriate to variable type
Daily Quiz #1
Do problem R-2.10 (p. 96) from the book
Polygons
Consider polygon classes:Rectangle, Square, Triangle, …
Want generic Polygon classSuperclass for all these classesMake arrays of Polygons possibleEnables Polygon as method
parameter
Polygons
Polygons have at least two common methods: float area() and float
circumference()But their implementation is class
specific How can we do this?
Polygon Class
public abstract class Polygon { public abstract double area(); public abstract double circumference();
public boolean isPlanar() { return true; }}
Abstract methods have no bodyServe as placeholder for subclasses to defineGuarantee minimal class functionality
Abstract Class
Abstract classes cannot be instantiatedAny class could be declared abstract
Subclass need not override all abstract methodsBut subclass will also be abstract
Can instantiate subclasses of abstract class only if all inherited abstract methods overriden
Square Class
public class Square extends Polygon { protected double side; public Square() { this(1.0); } public Square(double length) { side=length; } public double area() { return side * side; } public double circumference() { return side * 4; } public double getLength() { return side; } public double getWidth() { return side; }}
Can we instantiate Square?
Benefits of Abstract Classes
Polygon[] polys = new Polygon[3];polys[0] = new Square(2.0);polys[1] = new Triangle(...);polys[2] = new Square(5.6);
double total_area=0.0;for (int i=0; i<shapes.length; i++) total_area += shapes[i].area();
Abstract Class Summary
Abstract classes can contain fields, abstract methods, and normal methodsSuperclass can specify common
functionality Subclasses required to implement methodsAny class with abstract method(s) is
abstract
Abstract Class Summary
Abstract class cannot be instantiatedBut class can be extendedSubclasses could then be instantiated
Declaring methods abstract forces subclasses to implement themCan be goodCan be bad
Public Methods(Explicitly Stated)(Important!)
Interfaces
Interface is Java’s way to define an ADT Design document for external class features
Class Details(HIDDEN!)(What do I care?)
Interfaces
Interfaces declare public abstract methodsCannot define any other methods
Interfaces can declare fieldsFields have constant value (public static final)
Classes implement interfacesClass can implement more than 1 interfaceMust implement all the interfaces’ methods
Methods in an Interface
All methods are abstractAdding abstract qualifier is optional
Methods cannot have any implementation Implementation left strictly to Classes
Methods public by defaultMethods cannot be native, static, synchronized, or final
Goal of Interface
We want Polygons to be drawableBut want to make other classes drawable, too
Could make an abstract Drawable classClasses can’t extend Polygon AND Drawable
Solution: Make Drawable an interface!Provides way of multiple inheritence
Declaring Interfaces
public interface Drawable { public void setColor(Color c); public void setPosition(double x, double y); public void draw(Graphics g);}
public interface TransparentDrawable extends Drawable { public void setTransparency(int tLevel);}
Using Interfaces
public class DrawableSquare extends Square implements Drawable {private Color c;private double x,y;
public DrawableSquare(double length) { super(length); }public void setColor(Color col) { c = col; }
public void setPosition (double x_pos, double y_pos) { x=x_pos; y=y_pos;}
public void draw(Graphics g) { g.drawRect(x, y, side, side, c);}
}
Benefits of Interfaces
public void drawRed(Drawable d, Graphics g) { d.setColor(red); d.draw(g);}
Which of these calls are legal?drawRed(new Square(4), g);drawRed(new SquareDrawable(4), g);drawRed(new TriangleDrawable(…), g);drawRed(new DrawableIcon(…), g);
Last Word on Interfaces
Interfaces can have sub-interfacesSub-interface extends its super-interface
Inherits all abstract methods and static final fields Can then further declare more to list
Classes implementing sub-interface automatically implement super-interface
Will need to implement all the abstract methods
Typecasting
Polygon square = new Sqare();
double r = square.getLength();
Won’t compile!! Variable square is declared to be Polygon
Can only use methods defined on PolygonDeclaration specifies which methods can runActual type determines which methods do run
How To Get a Square from a Polygon
Polygon c = new Square();
double l = ((Square)c).getLength();
Typecasting forces c to act like square This now compiles (and works) But be careful with this power
This also compiles, but will not work:int i = 9;double l = ((Square)i).getLength();
Widening Conversions
String s = new String(“hello”);
Object obj;
obj = s;
This is a widening conversionAssigns a String to variable of superclass type
Widening conversions are always legalBy inheritance, a String “is a” ObjectDo not need to perform any typecasting
Narrowing Conversions
String s = new String(“bye”);
Object obj = s;
String t = obj; // NO! NO! NO!
Java cannot perform narrowing coversionsAssigning superclass variable to subclass variableCannot always tell if this is legalMust be done using typecasting:String t = ((String)obj);