1 / 44

Slides Credit: Bruce, Danyluk and Murtagh

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

bernie
Download Presentation

Slides Credit: Bruce, Danyluk and Murtagh

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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

  2. 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

  3. 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

  4. 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

  5. An Interactive Card Game Note the small framed display areas in this game interface

  6. Framed Displays current score “lives remaining” time remainingstart message

  7. 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

  8. 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

  9. 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

  10. 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

  11. 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

  12. 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();

  13. 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

  14. 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

  15. 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

  16. // 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(); } }

  17. 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

  18. 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

  19. 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( ... );

  20. Assuming the variable definitions: FramedDisplay someFrame; FramedText someText; FramedCounter someCounter; The following are also legal: someFrame = someText; someFrame = someCounter; someText = someCounter;

  21. 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

  22. 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 );

  23. what about someCounter = someFrame; someText = someFrame; and scoreDisplays.addFrame( someFrame );

  24. what about someCounter = someFrame; someText = someFrame; and scoreDisplays.addFrame( someFrame ); All Illegal

  25. 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 }

  26. 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.

  27. 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.

  28. 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

  29. 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(); }

  30. Can refer to any nonprivate method of a superclass with “super.methodname” in the definition of a subclass

  31. 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?

  32. 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

  33. 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

  34. 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

  35. 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

  36. 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

  37. 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 { ...

  38. 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

  39. Object-Oriented Design • Often software mimics the real world • Decompose problem into objects • identify properties and behaviors • model in software

  40. 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.

  41. 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.

  42. 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.

  43. 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

  44. 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!

More Related