440 likes | 528 Views
CS 120 Lecture 20. Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7),. 27 November 2012. Slides Credit: Bruce, Danyluk and Murtagh. Shared Features. Common to define classes that share features FilledRect and FramedRect
E N D
CS 120 Lecture 20 JavaObject Oriented ProgrammingEncapsulation, Inheritance, Polymorphism(Java: An Eventful Approach - Ch. 17, 21.7), 27 November 2012 Slides Credit: Bruce, Danyluk and Murtagh
Shared Features • Common to define classes that share features • FilledRect and FramedRect • Desirable to let classes with common features and behaviors share code • saves programmer time • improves code reliability
Inheritance • mechanism that provides means to share code in related classes • already familiar...sort of • classes that extend WindowController • inherit variables and other features from WindowController • canvas, getContentPane(), and others defined in WindowController class
Extension as Specialization • a class that extends another is a subclass • a class that is extended is a superclass • inheritance describes relationship between a subclass and superclass • subclass inherits features from superclass it extends • subclass will include every method and instance variable in superclass • subclass may also include new features • subclass like the superclass- but more special or specialized
An Interactive Card Game Note the small framed display areas in this game interface
Framed Displays current score “lives remaining” time remainingstart message
Design Choices • Could define independent class for each category of frame or • Better: • define class describing empty frame • extend it to define classes of specialized frames
Using extends • Say we want to display text in a frame • A FramedText class • if written from scratch, would repeat much of FramedDisplay • define as an extension of FramedDisplay
public class FramedText extends FramedDisplay • extends FramedDisplay • tells Java to include all instance variables and methods from FramedDisplay in FramedText • no need to redefine in new class • add what we need to manipulate Text object displayed in frame
Subclass Constructors • often want to • inherit behavior of superclass constructor • but also do more • write new constructor • begin with special instruction to invoke constructor of superclass ex. super( x, y, width, height, canvas ); • add statements to perform additional work desired
super • an invocation of super can only appear as first command in a constructor’s body • if invocation of super not included, Java inserts super(); automatically Note: Will result in error if class being extended has no parameterless constructor
Methods of subclasses can be used in the usual way. If we have private FramedText welcome; and execute welcome = new FramedText( “Hello”, 20, 20, 100, 30, canvas ); can legally execute welcome.setTextSize( 24 ); and welcome.highlight();
Access Control • public- can be accessed in other classes • private • only accessible within class in which defined • restriction applies even for subclasses; private name defined in superclass cannot be accessed in subclass • protected • accessible in classes that extend the one in which name defined
Designing for Extension • easy to imagine designing subclasses of FramedDisplay that will require info about • dimensions of parts of frame • locations of parts of frame • in designing interface for a class, must consider • what methods would be helpful to objects outside of the class • what would be useful to those extending the class • prefer protected accessor methods to protected variables • access to protected variables (if not final) allows changes that can lead to errors
Inheritance Hierarchies • Implement a FramedCounter class • display value of a counter (as in FramedText) • include an increment method • FramedCounter inherits features from FramedText • includes features that FramedText inherits from FramedDisplay
// A FramedCounter object displays a numeric counter on // a background framed by a distinct border public class FramedCounter extends FramedText { private int counter = 0; // Current value of counter // Create a FramedCounter object displaying 0 // at the position and with the dimensions specified public FramedCounter( double x, double y, double width, double height, DrawingCanvas canvas ) { super( “0”, x, y, width, height, canvas ); } // Increase the counter’s value and update display public void increment( int amount ) { counter = counter + amount; message.setText( counter ); positionContents(); } }
Subclasses and Superclasses • A is a superclass of B if • B extends A or • B extends C and A is a superclass of C • B is a subclass of A if • B extends A or • B extends C and C is a subclass of A
Subclass Type Compatibility • Can assign an object to a variable as long as type of object is either • same as type of variable or • a subclass of the variable type
Assume these variable definitions FramedDisplay someFrame; FramedText someText; FramedCounter someCounter; The following assignments are legal: someFrame = new FramedDisplay( ... ); someFrame = new FramedText( ... ); someFrame = new FramedCounter( ... ); someText = new FramedText( ... ); someText = new FramedCounter( ... ); someCounter = new FramedCounter( ... );
Assuming the variable definitions: FramedDisplay someFrame; FramedText someText; FramedCounter someCounter; The following are also legal: someFrame = someText; someFrame = someCounter; someText = someCounter;
Parameter Compatibility • Same rules apply • Actual parameter compatible with formal parameter as long as • its type is same as type of formal parameter or • its type is a subclass of the formal parameter type
Assuming the variable definitions: FramedDisplay someFrame; FramedText someText; FramedCounter someCounter; And a collection class with method: public void addFrame( FramedText someText ) { ... the following are legal for an object of the collection type scoreDisplays.addFrame( someText ); scoreDisplays.addFrame( someCounter );
what about someCounter = someFrame; someText = someFrame; and scoreDisplays.addFrame( someFrame );
what about someCounter = someFrame; someText = someFrame; and scoreDisplays.addFrame( someFrame ); All Illegal
Checking Types • Consider someFrame = new FramedCounter( ... ); someCounter = someFrame; someText = someFrame; scoreDisplays.addFrame( someFrame ); • last 3 lines still considered illegal by Java. • If programmer confident variable of correct type can introduce type cast someCounter = (FramedCounter) someFrame; • To ensure type cast can be done if ( someFrame instanceof FramedCounter ) { someCounter = (FramedCounter) someFrame }
Overriding Method Definitions • Sometimes need to change behavior of methods in superclass for proper functionality in subclass. • define method in body of subclass with same name • new method is said to override the original method.
The Object Class • Java class Object is a superclass of all Java classes • All classes inherit certain methods from Object • equals: version defined in Object compares using == ; can override to tailor behavior of equals for a class • toString: returns a String describing the object on which it is invoked; often useful to override.
Accessing Overridden Methods • sometimes want to extend- not totally change- steps performed by a method in a superclass. • super as a means to access an overridden method from within a subclass
Using super Say we have added a move method to FramedDisplay // Move the parts of the framed display by offsets public void move( double xoff, double yoff ) { border.move( xoff, yoff ); body.move( xoff, yoff ); } Can override this method in FramedText as follows: // Move the display by specified offsets public void move( double xoff, double yoff ) { super.move( xoff, yoff ); // Move the body and border positionContents(); }
Can refer to any nonprivate method of a superclass with “super.methodname” in the definition of a subclass
Dynamic Method Invocation Say we declare private FramedDisplay someFrame; and later execute someFrame = new FramedText( “Follow me”, 50, 50, 80, 25, canvas ); someFrame.move( 100, 50 ); Which version of move is executed? • the version in FramedDisplay? • the version in FramedText?
Dynamic Method Invocation Say we declare private FramedDisplay someFrame; and later execute someFrame = new FramedText( “Follow me”, 50, 50, 80, 25, canvas ); someFrame.move( 100, 50 ); Which version of move is executed? • the version in FramedDisplay? • the version in FramedText
Java invokes the version of a method associated with an object’s class regardless of the type of name through which it is accessed • process of identifying correct method is called dynamic method invocation
A More Complex Example Say we define moveTo in FramedDisplay public void moveTo( double x, double y ) { this move( x - border.getX(), y - border.getY() ); } • Java interprets this dynamically • invocation refers to move method of this, the object whose moveTo was invoked If we execute FramedText welcomeMessage = new FramedText( “Click to begin”,... ); welcomeMessage.moveTo( centerX, centerY ); move in FramedText is used
Design Suggestions • Sometimes useful to define a method of a superclass with the expectation it will be overridden • Consider adding the following to FramedDisplay • move, as before • setWidth, setHeight Subclasses will need to override all of these for correct functionality
Better Design • Define positionContents method in FramedDisplay: protected void positionContents( ) { } • Define move as: // Move the parts of the framed display by offsets public void move( double xoff, double yoff ) { border.move( xoff, yoff ); body.move( xoff, yoff ); positionContents(); } • If setWidth and setHeight defined similarly, only positionContents needs to be overridden in subclasses
Abstract Classes and Methods • Abstract class • provides base for defining useful subclasses • not useful by itself • We defined positionContents in FramedDisplay to ensure that subclasses of FramedDisplay would define it • Unsatisfying to define an empty method • Could replace definition of positionContents with abstract protected void positionContents() ; and make class abstract public abstract class FramedDisplay { ...
Object-Oriented Design • Given the description of a problem, • how do you determine what classes to define? • how do you design each class? • Need a design methodology
Object-Oriented Design • Often software mimics the real world • Decompose problem into objects • identify properties and behaviors • model in software
Abstraction • An object provides an abstraction • can use without knowing details of its implementation • abstract away details; understand at higher level • Follows from our use of objects in real world • can use a stopwatch without knowing exactly how it works • Well-designed classes provide good abstractions.
Encapsulation • notion of taking variables and data structures and wrapping them inside a class definition Information Hiding • notion of hiding details of implementation as much as possible • Eg. Users of our Triangle class don’t need to know HOW it stores the triangle.
Why Important? • protects variables from being modified inappropriately by other classes • can present classes to others for use by simply specifying interface ex. You used objectdraw library without knowing any implementation details! • can change details of class definition without affecting those using it.
Writing Comments • Each class should have a class comment • Description of class • Author’s name and date • Each constant and variable should be commented • describe purpose (what, not how!) • parameters • return value, if any • For long/complex methods • include comments in method • explain what is happening • balance clarity and brevity
Student To Do’s • HW10 • Green Screen program. • Review Lab 10 to get started. • There is a grading criteria, check it! • Includes both style and commenting • Try to get your web page online. • Java Project – • Due 12/12 • Practice examples on your own!