Highlights of Last Week

Similar documents
Highlights of Previous Lecture

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Highlights of Last Week

1 Shyam sir JAVA Notes

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Highlights of Previous Lecture

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

INHERITANCE. Spring 2019

CSC Java Programming, Fall Java Data Types and Control Constructs

CISC370: Inheritance

CMSC 132: Object-Oriented Programming II

Distributed Systems Recitation 1. Tamim Jabban

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Abstract Classes and Interfaces

C a; C b; C e; int c;

Inheritance (Part 5) Odds and ends

What is Inheritance?

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

COP 3330 Final Exam Review

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. January 11, 2018

Inheritance (continued) Inheritance

Introduction to Programming Using Java (98-388)

CS Programming I: Inheritance

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

CS260 Intro to Java & Android 03.Java Language Basics

Computer Science II (20073) Week 1: Review and Inheritance

Big software. code reuse: The practice of writing program code once and using it in many contexts.

CO Java SE 8: Fundamentals

Java Magistère BFA

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

CS 251 Intermediate Programming Inheritance

CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017

Brief Summary of Java

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

C12a: The Object Superclass and Selected Methods

Prelim 1 SOLUTION. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants. Recursion OO Short answer

Goals for Today. CSE1030 Introduction to Computer Science II. CSE1030 Lecture #9. Review is-a versus has-a. Lecture #9 Inheritance I

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Lecture Notes Chapter #9_b Inheritance & Polymorphism

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at Interfaces.

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Declarations and Access Control SCJP tips

15CS45 : OBJECT ORIENTED CONCEPTS

Object Oriented Programming

Inheritance and Polymorphism

CS-202 Introduction to Object Oriented Programming

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Class, Variable, Constructor, Object, Method Questions

CSCI 136 Written Exam #0 Fundamentals of Computer Science II Spring 2015

Super-Classes and sub-classes

F I N A L E X A M I N A T I O N

Lecture 2: Java & Javadoc

CS Programming Language Java. Fall 2004 Sept. 29

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Java Fundamentals (II)

CH. 2 OBJECT-ORIENTED PROGRAMMING

Inheritance & Polymorphism

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

Computer Science II (20082) Week 1: Review and Inheritance

Implements vs. Extends When Defining a Class

Distributed Systems Recitation 1. Tamim Jabban

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Today. Book-keeping. Exceptions. Subscribe to sipb-iap-java-students. Collections. Play with problem set 1

CLASS DESIGN. Objectives MODULE 4

Inheritance (Part 2) Notes Chapter 6

Create a Java project named week10

CMSC 132: Object-Oriented Programming II. Inheritance

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

In this lab we will practice creating, throwing and handling exceptions.

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Index COPYRIGHTED MATERIAL

Programming Exercise 14: Inheritance and Polymorphism

JAVA MOCK TEST JAVA MOCK TEST III

The Java language has a wide variety of modifiers, including the following:

Java Classes. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Topic 7: Inheritance. Reading: JBD Sections CMPS 12A Winter 2009 UCSC

CIS 110: Introduction to computer programming

CS61BL Summer 2013 Midterm 2

20 Most Important Java Programming Interview Questions. Powered by

Programming overview

Chapter 6 Introduction to Defining Classes

Selected Questions from by Nageshwara Rao

Software and Programming 1

C# Programming for Developers Course Labs Contents

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Java classes cannot extend multiple superclasses (unlike Python) but classes can implement multiple interfaces.

MODULE 6q - Exceptions

Transcription:

Highlights of Last Week Refactoring classes to reduce coupling Passing Object references to reduce exposure of implementation Exception handling Defining/Using application specific Exception types 1

Sample Homework Solution - PlaneId PlaneId.java /** A class that maintains a relationship between an Airplane and ** and Airline to identify a particular plane public class PlaneId { /** Identify an Airline / Airplane combination */ private String planeidentifier; public PlaneId (Airline airline, Airplane plane) { // PlaneId internally is simply the space separated // concatenation of the airline name with the plane id planeidentifier = airline.getname() + " " + plane.getid(); /** Returns a hashcode that identifies this PlaneId */ public int hashcode() { return planeidentifier.hashcode(); /** Compares this PlaneId to the specified object */ public boolean equals(object o) { if (o instanceof PlaneId) { PlaneId po = (PlaneId) o; if (hashcode() == po.hashcode()) return true; return false; /** Return a string identifing this PlaneId instance */ public String tostring() { return planeidentifier; 2

protected String getplaneidentifier() { return planeidentifier; 3

Sample Homework Solution - AirTrafficController AirTrafficController.java import java.util.hashmap; import java.util.set; import java.util.iterator; // interface // interface public class AirTrafficController { private HashMap planeidsbeingmonitored = new HashMap(); /** Causes the AirTrafficController to remember a planeid. public void monitor(planeid pid) throws InvalidPlaneIdException { if (planeidsbeingmonitored.containskey(pid)) { // The plane id is already being monitored by this // AirTrafficController. // This is probably an error. throw new InvalidPlaneIdException(pid.toString() + " is already being monitored"); else { // Remember this planeid planeidsbeingmonitored.put(pid, pid); /** Provide some way for the AirTrafficController to stop ** monitoring a PlaneId. public PlaneId remove(planeid id) { return id; 4

public Iterator getplaneids() { Set s = planeidsbeingmonitored.keyset(); return s.iterator(); public String tostring() { Set s = planeidsbeingmonitored.keyset(); Iterator i = s.iterator(); StringBuffer b = new StringBuffer("Monitoring: "); boolean first = true; while (i.hasnext()) { PlaneId p = (PlaneId) i.next(); if (! first) b.append(", "); else first = false; // from here on b.append(p.tostring()); return b.tostring(); 5

Sample Homework Solution - InvalidPlaneIdException InvalidPlaneIdException.java /** This exception is thrown when a plane id is invalid ** for some reason. public class InvalidPlaneIdException extends Exception { public InvalidPlaneIdException() { public InvalidPlaneIdException(String msg) { super(msg); 6

Sample Homework Solution - AirTrafficTest AirTrafficTest.java import java.util.iterator; import java.util.hashmap; import java.util.arraylist; import java.util.collection; import java.util.set; // interface // interface /** A class that will be used to test Airline, Airplane, ** PlaneId and AirTrafficController capabilities. public class AirTrafficTest { /** Keeps track of airline names and the number of ** airplanes for each. private HashMap airlineinfo = new HashMap(); /** Keeps track of the airline names and the ** corresponding Airline objects themselves. protected HashMap airlines = new HashMap(); /** The two Maps somewhat duplicate the information ** that is kept for an Airline in two places. A ** better approach might be to create a helper class, ** instances of which would encapsulate the ** information we want to maintain for an Airline. ** However, this way keeps things a bit simpler. /** Keeps track of the AirTrafficControllers */ protected ArrayList controllers = null; /** Constructor */ protected AirTrafficTest() { /** Creates the desired number of ** AirTrafficControllers. 7

void createcontrollers(int numcontrollers) { controllers = new ArrayList(numControllers); for ( ; numcontrollers > 0; numcontrollers--) { AirTrafficController c = new AirTrafficController(); controllers.add(c); /** Save an airline name and the number of planes the ** airline will have. void saveairlineinfo(string name, int numplanes) { // put into the name-th slot of the airlineinfo Map // the number of planes that the airline will have. // Note only objects can be saved in a collection, so // the number of planes is wrapped in an instance of // java.lang.integer. No allowance is made for a // duplicate airline name; later occurances of the // name simply replace previous occurances. airlineinfo.put(name, new Integer(numPlanes)); /** Iterate through the Map of airlineinfo and create ** airlines, saving a reference to each Airline ** created. These references are saved simply to ** enable them to be identified later. void createairlines() { Set s = airlineinfo.keyset(); Iterator iter = s.iterator(); while (iter.hasnext()) { // set of airline names // one at a time // Create a new Airline String name = (String) iter.next(); Airline a = new Airline(name); // and save it to give airplanes to later airlines.put(name, a); // What happens to the Set and the Iterator objects? 8

/** Iterate through the Map of airlineinfo and create ** the desired number of airplanes, adding them to the ** airline. void createairplanes() { Set s = airlineinfo.keyset(); Iterator iter = s.iterator(); int serialnum = 1; // set of airline names // one at a time // for airplane ids while (iter.hasnext()) { String name = (String) iter.next(); // airlineinfo map associates airline names with // number of airplanes requested Integer numplanes = (Integer) airlineinfo.get(name); // airline map associates airline name with the // airline object Airline airline = (Airline) airlines.get(name); for (int i = numplanes.intvalue(); i > 0; i--) { // Create the next Airplane, giving it the next // serial number for an id (with the serial // number represented as a String. Airplane plane = // sequentially "number" airplanes new Airplane( Integer.toString(serialNum++)); // add the airplane to the airline airline.addairplane(plane); /** Iterate through the Map of airlines, ask each for ** an iterator of its planes, and create PlaneId ** objects for each assigning those to ** AirTrafficControllers. void assignairplanes() { Set s = airlines.keyset(); Iterator airlineiter = s.iterator(); 9

int controllerindex = 0; while (airlineiter.hasnext()) { String name = (String) airlineiter.next(); // next airline name // Get the next airline object by name Airline airline = (Airline) airlines.get(name); Iterator airplaneiter = airline.airplaneiterator(); while (airplaneiter.hasnext()) { Airplane plane = (Airplane) airplaneiter.next(); // Create the PlaneId PlaneId pid = new PlaneId(airline, plane); // Assign it to an AirtrafficController AirTrafficController c = (AirTrafficController) controllers.get(controllerindex); try { c.monitor(pid); catch (InvalidPlaneIdException e) { // Shouldn t happen System.err.println(e); // Get ready to assign next controllerindex++; controllerindex = controllerindex % controllers.size(); void identifyairlines(java.io.printstream out) { // Cause the Airline objects and the Airplane objects to // identify themselves and, in the case of the Airplanes, // their current cost per seat. Collection c = airlines.values(); Iterator airlineiter = c.iterator(); while (airlineiter.hasnext()) { Airline a = (Airline) airlineiter.next(); out.println(a.tostring()); 10

void identifycontrollers(java.io.printstream out) { // Cause the AirTrafficController objects to identify // themselves. They will in turn identify the // PlaneIds they are monitoring. for (int i = 0; i < controllers.size(); i++) { AirTrafficController atc = (AirTrafficController) controllers.get(i); out.print("controller " + i + " "); out.println(atc.tostring()); void performtests(string[] args) { int arg = 0; int numcontrollers = 0; // Parse the application s arguments from the command // line. The Integer.parseInt method calls (to // convert the String arguments into int primitives) // may result in NumberFormatExceptions being thrown. try { // First, determine how many controllers are desired numcontrollers = Integer.parseInt(args[0]); createcontrollers(numcontrollers); // Next, save the names of the airlines and the // desired number of planes for each. for ( arg = 1; arg < args.length; arg+= 2) { // Name of airline String name = args[arg]; // Number of planes int numplanes = Integer.parseInt(args[arg+1]); saveairlineinfo(name, numplanes); catch (NumberFormatException e) { System.out.println(args[arg+1] + " not an integer"); e.fillinstacktrace(); // record where this occured throw e; // bailout and let JVM report it 11

// Time to create the airlines createairlines(); // and their airplanes createairplanes(); // Assign Airplanes to controllers assignairplanes(); // show the state of the air traffic controllers identifycontrollers(system.out); public static void main(string[] args) { String usage = "usage: AirTrafficTest number_of_controllers " + "[airline_name number_of_planes]..."; if ( args.length < 3 args.length % 2 == 0 ) { System.out.println(usage); else { AirTrafficTest tester = new AirTrafficTest(); tester.performtests(args); 12

Inheritance - classes that are defined in terms of other classes You say one class extends another when you want to re-use most of the capabilities of a class, but want to add some additional capabilities, over-ride some, or provide other specialization. The purpose of inheritance is specialization. Inheritance models the "IS-A" (or "IS-A-KIND-OF") relationship Textbook Issue, p 127: "This is one of the significant ways to achieve productivity with an object-oriented language: find a built-in class that does much of what you need, and create a subclass of that class, adding just those features that you need for your own purposes;..." Guideline: Not unless your subclass "IS-A-KIND-OF" the parent class. 13

java.lang.object Every Java class implicitly extends Object. The least specialized class is sometimes called the base, parent, or super class. Student.java /** A Java class that models information common to all ** student types. ** @author Jonathan Doughty public class Student /* extends Object */ { // Fields associated with an individual Student object. private String name; private String id; private double tuitionpaid = 0.0; // Constructor for Student objects public Student(String newstudentname, String id) { name = newstudentname; this.id = id; /** Method called when asking Student s to pay their bills public void paytuition(double amount) { tuitionpaid += amount; // remainder of paying tuition left as an exercise public String getname() { return name; 14

Object getid() { return id; public String tostring() { String result = "Student name: " + name + " Id: " + id; result += " tuition paid:" + tuitionpaid; return result; //... other methods common to all Students 15

Inheriting methods A more specialized class extends the super class. The more specialized class is sometimes called the derived or child class. CSStudent.java import java.util.hashmap; /** A Java class that models information kept about a CS ** student. This CSStudent class inherits capabilities ** that all students share from the base class. ** @author Jonathan Doughty ** @version 3.0 public class CSStudent extends Student { // Fields associated with the CSStudent specialization of // Students. private CSStudent private HashMap labpartner = null; homeworkgrades = new HashMap(); // Constructor for CSStudent objects public CSStudent(String newstudentname, String id) { super(newstudentname, id); // Look mom, no paytuition() method // Nor getname(), getid() either. // Derived classes get those for free. public String tostring() { String endl = System.getProperty("line.separator"); String result = super.tostring(); if (labpartner!= null) result += " Lab partner: " + labpartner.getname(); 16

if (homeworkgrades.size() > 0) { result += endl + " Homework grades: "; for (int i = 0; i < homeworkgrades.size(); i++) { Integer k = new Integer(i); result += " " + i + "-" + homeworkgrades.get(k); return result; // Since these are "package protected" (without an explicit // accessability modifier) only classes in the same package can // invoke these methods. void assignpartner(csstudent partner) { labpartner = partner; void assignhomeworkgrade( int assignmentnumber, String grade) { Integer assignment = new Integer(assignmentNumber); homeworkgrades.put(assignment, grade); 17

Derived classes Derived classes inherit methods from their base class(es) There is no requirement, if the derived class is not going to add any specialization to a method defined in the base class, for the derived class to have an implementation of the method. The derived class should certainly not duplicate the logic of the base class s method implementation. 18

Super The super keyword allows a class to use the immediate parent class constructors and to access accessible over-ridden fields, and methods. The derived class only has access via super to the class it extends, not to any classes that that class may extend. super will access only the most immediate method implementation. Note that derived classes may override methods of any of the base classes to redefine the implementation. Derived classes may also add methods not defined in any base class. CSGradStudent.java /** Encapsulate the characteristics of a CS Grad student ** @author: Jonathan Doughty public class CSGradStudent extends CSStudent { private boolean isteachingassistant = false; private Amount fellowshipvalue = new Amount(10000.0); // constructor public CSGradStudent( String studentname, String id) { super(studentname, id); // override base class s (actually base class s base // class) implementation. You can over-ride any method // defined by a parent class up to and incuding // java.lang.object methods. public void paytuition(double tuitionamount) { super.paytuition(tuitionamount); fellowshipvalue = new Amount( fellowshipvalue.getasdouble() - tuitionamount); 19

void writethesis() { // mumble void appointta() { isteachingassistant = true; public String tostring() { return "Grad:" + super.tostring(); // Other methods associated with being a grad student... 20

Abstract: Forcing a class to be extended You can force users of a class you create to sub-class your class to be able to use it by qualifying your parent class (and/or possibly some or all of the methods as abstract. Abstract classes may provide implementations of some or all methods You can t instantiate objects of an abstract class // compiler error: SomeAbstractClass abstractclassobject = new SomeAbstractClass() Why would an abstract class be desirable? When it doesn t make sense to have objects of the base class When default implementations of some methods or fields are desirable. The Student.java class should probably be abstract 21

Using Abstract Class References You can assign objects of a derived class to a reference of an abstract class type // Okay: SomeAbstractClass abstractclassobject = new SomeNonAbstractDerivedClass() Why would an abstract class reference be desirable? When you want to treat all objects of derived types in the same way When you want to handle objects polymorphically 22

Accessability - Protected The protected accessability modifier methods are only callable from the methods of the class and any derived classes. variables are accessable within the instance methods of the class and any derived classes. Note that you can derive from a class that is in a different package So protected can make implementation details visible to out of package classes. 23

Inheritance Example - Unique Plane Ids UniquePlaneId.java /** A class that maintains a relationship between an ** Airplane and and Airline to identify a particular plane ** uniquely. import java.util.hashmap; public class UniquePlaneId extends PlaneId { private static HashMap usedids = new HashMap(); // Save the unique id for each UniquePlaneId instance. // The "final" says uniqueidentifier can only be assigned // to once. private final String uniqueidentifier; public UniquePlaneId (Airline airline, Airplane plane) throws InvalidPlaneIdException { // Invoke parent class s constructor super(airline, plane); // The "super." below is only to make explicit where // getplaneidentifier() comes from. "super." is not // needed. (unless this class had an over-riding // getplaneidentifier() method.) uniqueidentifier = super.getplaneidentifier(); if (usedids.get(uniqueidentifier)!= null) { throw new InvalidPlaneIdException( uniqueidentifier + " already in use"); 24

else { usedids.put(uniqueidentifier, uniqueidentifier); /** When/if the garbage collector reaps this ** UniquePlaneId finalize will insure the saved ** uniqueidentifier gets forgotten as well. protected void finalize() { usedids.remove(uniqueidentifier); 25

Inheritance In Use AirTrafficUniqueTest.java import java.util.iterator; import java.util.set; // interface public class AirTrafficUniqueTest extends AirTrafficTest { /** Iterate through the Map of airlines, ask each for an ** iterator of its planes, and create UniquePlaneId ** objects for each assigning those to ** AirTrafficControllers. void assignairplanes() { Set s = airlines.keyset(); Iterator airlineiter = s.iterator(); int controllerindex = 0; Airline airline = null; Airplane plane = null; while (airlineiter.hasnext()) { String name = (String) airlineiter.next(); // next airline name // Get the next airline object by name airline = (Airline) airlines.get(name); Iterator airplaneiter = airline.airplaneiterator(); while (airplaneiter.hasnext()) { plane = (Airplane) airplaneiter.next(); // Create the UniquePlaneId try { // Note that a UniquePlaneId can be assigned to a // field of type PlaneId: a UniquePlaneId IS-A // PlaneId. 26

PlaneId pid = new UniquePlaneId(airline, plane); // Assign it to an AirtrafficController AirTrafficController c = (AirTrafficController) controllers.get(controllerindex); c.monitor(pid); catch (InvalidPlaneIdException e) { // Shouldn t happen System.err.println(e); // Get ready to assign next controllerindex++; controllerindex = controllerindex % controllers.size(); // Try to create one last UniquePlaneId with the same // airline and plane as the last try { PlaneId id = new UniquePlaneId(airline, plane); catch (InvalidPlaneIdException e) { // Should happen System.err.println( "Success: caught attempt to make a non-unique " + e ); public static void main(string[] args) { String usage = "usage: AirTrafficUniqueTest number_of_controllers " + "[airline_name number_of_planes]..."; if ( args.length < 3 args.length % 2 == 0 ) { System.out.println(usage); else { AirTrafficUniqueTest tester = new AirTrafficUniqueTest(); 27

tester.performtests(args); 28

Final: preventing a class or method from being extended final classes The keyword final has two uses: it can be used to mark a class, much as the abstract keyword is used: public final class SomeClass {... A class marked final can not be extended Why would a final class be desirable? When you don t want to allow sub classes. Final methods The keyword final can also be applied to individual methods: public class SomeClass {... public final double getsalary() {... A method marked final can not be overridden in a derived class. Marking a method final does not prevent creating derived classes Why would a final method be desirable? 29

When you don t want to allow sub classes to over-ride certain, required behavior 30

Homework 5 Reading Chapter 6 - Collections of Objects Chapter 7 - Some Final Concepts Programming No specific programming assignment this week If you want to get a jump on next week s assignment, study and understand inheritance and abstract classes using tonight s examples. 31