Objects First With Java - Chapter 8

Objects First With Java - Chapter 8

Improving structure with inheritance 5.0 Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 2 The Network example A small, prototype social network. Supports a news feed with posts. Stores text posts and photo posts. MessagePost: multi-line text message. PhotoPost: photo and caption. Allows operations on the posts: E.g., search, display and remove. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling

3 Network objects Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 4 Network classes Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 5 Network object model

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 6 Class diagram Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 7 Message -Post source code

public class MessagePost { private String username; private String message; private long timestamp; private int likes; private ArrayList comments; public MessagePost(String author, String text) { username = author; message = text; timestamp = System.currentTimeMillis(); likes = 0; comments = new ArrayList(); }

Just an outline public void addComment(String text) ... public void like() ... public void display() ... ... } Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 8 PhotoPost source code

public class PhotoPost { private String username; private String filename; private String caption; private long timestamp; private int likes; private ArrayList comments; public PhotoPost(String author, String filename, String caption) { username = author; this.filename = filename; this.caption = caption; timestamp = System.currentTimeMillis();

likes = 0; comments = new ArrayList(); } Just an outline public void addComment(String text) ... public void like() public void display() ... } Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 9

NewsFeed public class NewsFeed { private ArrayList messages; private ArrayList photos; ... public void show() { for(MessagePost message : messages) { message.display(); System.out.println(); // empty line between posts } for(PhotoPost photo : photos) { photo.display(); System.out.println(); // empty line between posts }

} } Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 10 Critique of Network Code duplication: MessagePost and PhotoPost classes very similar (large parts are identical) makes maintenance difficult/more work introduces danger of bugs through incorrect maintenance

Code duplication in NewsFeed class as well. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 11 Using inheritance Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 12 Using inheritance define one superclass : Post

define subclasses for MessagePost and PhotoPost the superclass defines common attributes (via fields) the subclasses inherit the superclass attributes the subclasses add other attributes 13 Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling Inheritance hierarchies Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling

14 Inheritance in Java public class Post { ... } no change here change here public class PhotoPost extends Post { ...

} public class MessagePost extends Post { ... } Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 15 Superclass public class Post { private String username; private long timestamp; private int likes; private ArrayList comments;

// constructor and methods omitted. } Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 16 Subclasses public class MessagePost extends Post { private String message; // constructor and methods omitted. } public class PhotoPost extends Post { private String filename;

private String caption; // constructor and methods omitted. } Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 17 Inheritance and constructors public class Post { private String username; private long timestamp; private int likes;

private ArrayList comments; /** * Initialize the fields of the post. */ public Post(String author) { username = author; timestamp = System.currentTimeMillis(); likes = 0; comments = new ArrayList(); } // methods omitted } Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling

18 Inheritance and constructors public class MessagePost extends Post { private String message; /** * Constructor for objects of class MessagePost */ public MessagePost(String author, String text) { super(author); message = text; }

// methods omitted } Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 19 Superclass constructor call Subclass constructors must always contain a 'super' call. If none is written, the compiler inserts one (without parameters) works only, if the superclass has a constructor without parameters Must be the first statement in the

subclass constructor. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 20 Adding more item types Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 21 Deeper hierarchies Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 22

Review (so far) Inheritance (so far) helps with: Avoiding code duplication Code reuse Easier maintenance Extendibility Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 23 public class NewsFeed { private ArrayList posts; /**

* Construct an empty news feed. */ public NewsFeed() { posts = new ArrayList(); } /** * Add a post to the news feed. */ public void addPost(Post post) { posts.add(post); } ... Revised

NewsFeed source code avoids code duplication in the client class! } Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 24 New NewsFeed source

code /** * Show the news feed. Currently: print the * news feed details to the terminal. * (Later: display in a web browser.) */ public void show() { for(Post post : posts) { post.display(); System.out.println(); // Empty line ... } } Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling

25 Subtyping First, we had: public void addMessagePost( MessagePost message) public void addPhotoPost( PhotoPost photo) Now, we have: public void addPost(Post post) We call this method with: PhotoPost myPhoto = new PhotoPost(...); feed.addPost(myPhoto); Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling

26 Subclasses and subtyping Classes define types. Subclasses define subtypes. Objects of subclasses can be used where objects of supertypes are required. (This is called substitution .) Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 27 Subtyping and assignment

subclass objects may be assigned to superclass variables Vehicle v1 = new Vehicle(); Vehicle v2 = new Car(); Vehicle v3 = new Bicycle(); Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 28 Subtyping and parameter passing

public class NewsFeed { public void addPost(Post post) { ... } } subclass objects may be used as actual parameters for PhotoPost(...);the superclass PhotoPost photo = new MessagePost message = new MessagePost(...);

feed.addPost(photo); feed.addPost(message); Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 29 Object diagram Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 30 Class diagram Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling

31 Polymorphic variables Object variables in Java are polymorphic. (They can hold objects of more than one type.) They can hold objects of the declared type, or of subtypes of the declared type. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 32

Casting We can assign subtype to supertype but we cannot assign supertype to subtype! Vehicle v; Car c = new Car(); v = c; // correct c = v; // compile-time error! Casting fixes this: c = (Car) v; (only ok if the vehicle really is a Car!) Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 33

Casting An object type in parentheses. Used to overcome 'type loss'. The object is not changed in any way. A runtime check is made to ensure the object really is of that type: ClassCastException if it isn't! Use it sparingly. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 34

Review Inheritance allows the definition of classes as extensions of other classes. Inheritance avoids code duplication allows code reuse simplifies the code simplifies maintenance and extending Variables can hold subtype objects.

Subtypes can be used wherever supertype objects are expected (substitution). Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 35

Recently Viewed Presentations

  • Mucosal Alpha-Galactosylceramide Delivery Overcomes NKT cell ...

    Mucosal Alpha-Galactosylceramide Delivery Overcomes NKT cell ...

    ) is a potent activator of natural killer T (NKT) cells. NKT cells are a major innate immune mediator cell type effective in inducing maturation of dendritic cells (DC) for efficient presentation of co-administered antigens. Talk about analogs
  • Open Standards for Physical Asset Management OGI Pilot

    Open Standards for Physical Asset Management OGI Pilot

    Use Cases ISDD Based Way of Specifying, Selecting and Buying Devices and Equipment. Use Case. Adding As-Built Information Using OIIE Events. Adding Detail to Prior Work. As-Designed O&M Takeoff using CCOM or Proteus. Debutanizer Tower Condenser Unit P&ID. Worley Parsons:...
  • Physical Properties - Winthrop Chemistry

    Physical Properties - Winthrop Chemistry

    Protein Structure: Myoglobin as an Example John Kendrew solved the structure of myoglobin in 1959 No Computers! Myoglobin is a globular protein consisting of 153 amino acids and a prosthetic group: A Heme Myoglobin has no -sheets and is 100%...
  • Clergy and Laity Building God'S Kingdom Together Effective ...

    Clergy and Laity Building God'S Kingdom Together Effective ...

    clergy and laity building god's kingdom together"it's a partnership". fifth district lay convention. african methodist episcopal church. oakland marriott convention center. july 31, 2014. presenter . patricia m. mayberry
  • Funding Your Education Why go to college?  Explore

    Funding Your Education Why go to college? Explore

    This chart is for general information purposes only. Each program has specific requirements that are not listed on this chart. Prospective students should carefully review the requirements for each program through the links above and contact the university administering the...
  • BIOMASS FUTURES: Biomass role in achieving the Climate

    BIOMASS FUTURES: Biomass role in achieving the Climate

    Main steps are: Develop linkages to well established models (Admire- REBUS, BIOTRANS, PRIMES), harmonise data and assumptions and refine spatial resolution Quantify demand and supply dynamics through market segmentation (heat, electricity-CHP and transport) Provide indicators for indirect land use, air,...
  • Spelling, Punctuation and Grammar Revision Guide

    Spelling, Punctuation and Grammar Revision Guide

    Used to indicate a pause in speech or at the very end of a sentence so that words trail off into silence (this helps to create suspense). A pause in speech: "The sight was awesome… truly amazing." At end of...
  • The Efficiency of the Market

    The Efficiency of the Market

    Monopolists typically produce fewer goods and sell them at a higher price than under perfect competition, resulting in abnormal and sustained profit or what economists call . rent. A similar situation is an oligopoly, when only a few entities exert...