Highlights of Previous Lecture

Size: px
Start display at page:

Download "Highlights of Previous Lecture"

Transcription

1 Highlights of Previous Lecture Inheritance vs. Composition IS-A-KIND-OF vs. HAS-A relationships Java vs. C++: differences in ability to access base class behavior Interfaces as contracts, as types, supporting de-coupling Abstract classes vs. Interfaces 1

2 Highlights of Previous Meeting Design Patterns - nuggets of reusable software experience Intention Revealing Name - supports polymorphism Type Safe Enumeration - supports compile time checking Type Safe Homogeneous Collection- supports run time safety 2

3 Homework issues Comment your code more Provide a README file with instruction on running your program from the command line. Make sure your JAR archives are in the proper form. 3

4 Inheritance homework requirements Create three classes/types of air planes: BigPlane, MediumPlane, and SmallPlane. All three classes will have the following characteristics: An identifying string ("1", "2",... etc. is sufficient), A total number of seats. Once assigned this does not change for an Airplane though different Airplanes of the same type may have different total number of seats. A number of currently available seats. A cost per seat in each of several categories, see below. A method to change the cost per seat for a seat category. An implementation of the public String tostring() method that will return a String containing the type of airplane (Big, Medium, Small), the airplane ID and the current costs per seat. However, these three classes should differ from each other in the following ways: The total number of seats should be between for BigPlanes, for MediumPlanes, and 8-50 for SmallPlanes. Bigplanes and MediumPlanes should have three costs per seat, one each for FirstClass, BusinessClass, and EconomyClass. SmallPlanes should have only BusinessClass and EconomyClass cost per seat values. Create an abstract base class, AirPlane. Use this class to model the characteristics that are common to all three air plane classes above. You decide what belongs in the base class and what belongs in the specific classes. You should try to push as much common information into the base class. Unnecessary code duplication in derived classes is to be avoided. The base Airplane class should not have any knowledge of specific derived classes. 4

5 Modify the Airline class from the previous assignments, if necessary, to use AirPlane references. You may use my sample solution version or your own. The Airline objects should save the Airplane references in a collection class. The Airline class should not have any knowledge of specific classes derived from Airplane. Modify the test class from the second assignment or create a new test class to create several of each kind of airplane. Add these airplanes one at a time through a call to Airline s addairplane method to one or more Airline objects. (An airplane should only be added to one airline s collection.) Have each Airline object list all the Airplanes in its collection: their class, id, and current cost per seat values. 5

6 Inheritance homework solution - Abstract Base class Notice how, using a collection, the base class can deal with any number of seat categories. Notice how clients update and get seat costs by specifying a category. version1/airplane.java import java.util.iterator; import java.util.set; import java.util.hashmap; /** A base class to encapsulate information need for an ** airplane: its identifier, the number of seats (total ** and currently available) and the current costs per ** seat. public abstract class Airplane { private static int nextid = 0; /** An identifying number for the airplane */ private String id; /** The total number of seats */ private int totalseats; /** The number of currently available (un-sold) seats */ private int availseats; /** The current cost for a seat in several categories */ private HashMap costsperseat = new HashMap(3); // Each derived class has a minimum and and maximum number of seats private int lowrange; private int highrange; /** Create an airplane. seats initial capacity in seats low least seats plane will have high most seats plane will have protected Airplane(int seats, int low, int high) { if (seats < low seats > high) { 6

7 throw new IllegalArgumentException( seats + " seats is out of range " + low + " - " + high); this.id = String.valueOf(++nextId); this.totalseats = seats; availseats = totalseats; this.lowrange = low; this.highrange = high; /** Set the cost per seat to a new amount for a category. ** protected so that derived classes (posibly in other ** packages) can set their own seat cost. protected void setcostperseat(object category, double newcost) { Amount costpercategory = new Amount(newCost); costsperseat.put(category, costpercategory); /** Set the cost per seat to a new amount, but only for ** existing categories. Package protected so only ** objects in the same package can update the seat cost. void updatecostperseat(object category, double newcost) { if (! costsperseat.containskey(category)) { throw new IllegalArgumentException( getclass().getname() + " does not have a seat category \"" + category + "\""); // Replace it Amount costpercategory = new Amount(newCost); costsperseat.put(category, costpercategory); /** Get the cost per seat for a category */ double getcostperseat(object category) { Amount costforcategory = (Amount) costsperseat.get(category); if (costforcategory == null) { // someone asked for a category that doesn t exist throw new IllegalArgumentException( category + " seats don t exist for " + getclass().getname()); else return costforcategory.getasdouble(); /** Return the airplane s identifier as a String */ String getid() { 7

8 return id; // The platform specific end of line character: private static final String endl = System.getProperty("line.separator"); public String tostring() { StringBuffer buf = new StringBuffer("Airplane:"); buf.append(getid()); buf.append(" seats:"); buf.append(totalseats); buf.append(" avail:"); buf.append(availseats); Set keys = costsperseat.keyset(); for ( Iterator i = keys.iterator(); i.hasnext(); ) { Object key = i.next(); buf.append(endl); buf.append("\t"); buf.append(key); // calls tostring() on key buf.append(":"); double value = getcostperseat((string) key); buf.append(value); // calls tostring() on value (Amount) return buf.tostring(); 8

9 Inheritance homework solution - Derived classes Derived classes are little more than class constant definitions. version1/bigplane.java public class BigPlane extends Airplane { // Constants for seat categories; package protected so // that other classes in same package can request seat // cost changes, e.g., // plane.setcostperseat(bigplane.business_class, 550.); static final Object FIRST_CLASS = "FirstClass"; static final Object BUSINESS_CLASS = "BusinessClass"; static final Object ECONOMY_CLASS = "EconomyClass"; // Constants (instead of magic numbers) for initial costs private static final double INITIAL_FIRST_CLASS_COST = 500.; private static final double INITIAL_BUSINESS_CLASS_COST = 350.; private static final double INITIAL_ECONOMY_CLASS_COST = 200.; // Constants for allowable number of seats private static final int LEAST_SEATS = 200; private static final int MOST_SEATS = 300; private static final int DEFAULT_SEATS = 250; public BigPlane() { this(default_seats); public BigPlane(int numseats) { // Base class will check that numseats is within range super(numseats, LEAST_SEATS, MOST_SEATS); // Assign initial seat categories and costs setcostperseat(first_class, INITIAL_FIRST_CLASS_COST); setcostperseat(business_class, INITIAL_BUSINESS_CLASS_COST); setcostperseat(economy_class, INITIAL_ECONOMY_CLASS_COST); 9

10 public String tostring() { return "Big" + super.tostring(); version1/mediumplane.java public class MediumPlane extends Airplane { // Seat categories for this kind of Airplane static final Object FIRST_CLASS = "FirstClass"; static final Object BUSINESS_CLASS = "BusinessClass"; static final Object ECONOMY_CLASS = "EconomyClass"; // Constants (instead of magic numbers) for initial costs private static final double INITIAL_FIRST_CLASS_COST = 500.; private static final double INITIAL_BUSINESS_CLASS_COST = 350.; private static final double INITIAL_ECONOMY_CLASS_COST = 200.; // Constants for allowable number of seats private static final int LEAST_SEATS = 50; private static final int MOST_SEATS = 200; private static final int DEFAULT_SEATS = 150; public MediumPlane() { this(default_seats); public MediumPlane(int numseats) { // Base class will check that numseats is within range super(numseats, LEAST_SEATS, MOST_SEATS); // Assign initial seat categories and costs setcostperseat(first_class, INITIAL_FIRST_CLASS_COST); setcostperseat(business_class, INITIAL_BUSINESS_CLASS_COST); setcostperseat(economy_class, INITIAL_ECONOMY_CLASS_COST); 10

11 public String tostring() { return "Medium" + super.tostring(); version1/smallplane.java public class SmallPlane extends Airplane { // Seat categories for this kind of Airplane static final Object BUSINESS_CLASS = "BusinessClass"; static final Object ECONOMY_CLASS = "EconomyClass"; // Constants (instead of magic numbers) for initial costs private static final double INITIAL_BUSINESS_CLASS_COST = 200.; private static final double INITIAL_ECONOMY_CLASS_COST = 150.; // Constants for allowable number of seats private static final int LEAST_SEATS = 8; private static final int MOST_SEATS = 50; private static final int DEFAULT_SEATS = 25; public SmallPlane() { this(default_seats); public SmallPlane(int numseats) { // Base class will check that numseats is within range super(numseats, LEAST_SEATS, MOST_SEATS); setcostperseat(business_class, INITIAL_BUSINESS_CLASS_COST); setcostperseat(economy_class, INITIAL_ECONOMY_CLASS_COST); public String tostring() { return "Small" + super.tostring(); 11

12 Alternative solution - Abstract Base class Notice how the base class can require a method in the derived class. Notice how the base class relies on that required method to enforce some behavior. version2/airplane.java import java.util.iterator; import java.util.set; import java.util.hashmap; /** A base class to encapsulate information need for an ** airplane: its identifier, the number of seats (total ** and currently available) and the current costs per ** seat. public abstract class Airplane { private static int nextid = 0; /** An identifying number for the airplane */ private String id; /** The total number of seats */ private int totalseats; /** The number of currently available (un-sold) seats */ private int availseats; /** The current cost for a seat in several categories */ private HashMap costsperseat = new HashMap(3); // Each derived class has a minimum and and maximum number of seats private int lowrange; private int highrange; /** Create an airplane. seats initial capacity in seats low least seats plane will have high most seats plane will have protected Airplane(int seats, int low, int high, Iterator categories) { if (seats < low seats > high) { throw new IllegalArgumentException( 12

13 seats + " seats is out of range " + low + " - " + high); this.id = String.valueOf(++nextId); this.totalseats = seats; availseats = totalseats; this.lowrange = low; this.highrange = high; // Assign initial seat categories and costs while (categories.hasnext()) { Object category = categories.next(); costsperseat.put(category, new Amount(getInitialCost(category))); /** Return the initial cost for a seat in the specified category protected abstract double getinitialcost(object category); // This method will have to be implemented in every // derived class (or in at least one derived class that // others extend.) /** Set the cost per seat to a new amount, but only for ** existing categories. Package protected so only ** objects in the same package can update the seat cost. void updatecostperseat(object category, double newcost) { if (! costsperseat.containskey(category)) { throw new IllegalArgumentException( getclass().getname() + " does not have a seat category \"" + category + "\""); // Replace it Amount costpercategory = new Amount(newCost); costsperseat.put(category, costpercategory); /** Get the cost per seat for a category */ double getcostperseat(object category) { Amount costforcategory = (Amount) costsperseat.get(category); if (costforcategory == null) { // someone asked for a category that doesn t exist throw new IllegalArgumentException( category + " seats don t exist for " + getclass().getname()); else return costforcategory.getasdouble(); 13

14 /** Return the airplane s identifier as a String */ String getid() { return id; // The platform specific end of line character: private static final String endl = System.getProperty("line.separator"); public String tostring() { StringBuffer buf = new StringBuffer("Airplane:"); buf.append(getid()); buf.append(" seats:"); buf.append(totalseats); buf.append(" avail:"); buf.append(availseats); Set keys = costsperseat.keyset(); for ( Iterator i = keys.iterator(); i.hasnext(); ) { Object key = i.next(); buf.append(endl); buf.append("\t"); buf.append(key); // calls tostring() on key buf.append(":"); double value = getcostperseat((string) key); buf.append(value); // calls tostring() on value (Amount) return buf.tostring(); 14

15 Alternative solution - Derived classes Notice how base class and derived classes interact. version2/bigplane.java public class BigPlane extends Airplane { // Objects identifying seat categories static final Object FIRST_CLASS = "FirstClass"; static final Object BUSINESS_CLASS = "BusinessClass"; static final Object ECONOMY_CLASS = "EconomyClass"; // Limits on capacity of this kind of Plane private static final int LEAST_SEATS = 200; private static final int MOST_SEATS = 300; private static final int DEFAULT_SEATS = 250; // Initial costs for seat categories for this type Airplane. private static java.util.map initialcosts = new java.util.hashmap(3); // Initialize that information when class is loaded. static { initialcosts.put(first_class, new Double(500.)); initialcosts.put(business_class, new Double(350.)); initialcosts.put(economy_class, new Double(200.)); public BigPlane() { this(default_seats); public BigPlane(int numseats) { // Base class will check that numseats is within range super(numseats, LEAST_SEATS, MOST_SEATS, initialcosts.keyset().iterator()); 15

16 protected double getinitialcost(object category) { Double initialcost = (Double) initialcosts.get(category); if (initialcost!= null) return initialcost.doublevalue(); else throw new IllegalArgumentException( category + " not recognized for " + getclass().getname()); public String tostring() { return "Big" + super.tostring(); version2/mediumplane.java import java.util.hashmap; public class MediumPlane extends Airplane { // Limits on capacity of this kind of Plane private static final int LEAST_SEATS = 50; private static final int MOST_SEATS = 200; private static final int DEFAULT_SEATS = 150; // Objects that will be used to identify seat categories // for this type of Plane. static final Object FIRST_CLASS = "FirstClass"; static final Object BUSINESS_CLASS = "BusinessClass"; static final Object ECONOMY_CLASS = "EconomyClass"; // This information, shared among all the instances of // the class, will be used to assign initial costs for // each seat category for this type of Airplane. private static HashMap initialcosts = new HashMap(3); // This code block initializes that information the first // time the class is loaded. Since maps can only contain // objects, the cost values need to be wrapped in an // object type. static { initialcosts.put(first_class, new Double(400.)); initialcosts.put(business_class, new Double(300.)); 16

17 initialcosts.put(economy_class, new Double(200.)); public MediumPlane() { this(default_seats); public MediumPlane(int numseats) { // The base class will check that numseats is within // range and will call getinitialcosts to set seat // category costs for each category in the initialcosts // map. super(numseats, LEAST_SEATS, MOST_SEATS, initialcosts.keyset().iterator()); protected double getinitialcost(object category) { Double initialcost = (Double) initialcosts.get(category); if (initialcost!= null) return initialcost.doublevalue(); else throw new IllegalArgumentException( category + " not recognized for " + getclass().getname()); public String tostring() { return "Medium" + super.tostring(); version2/smallplane.java public class SmallPlane extends Airplane { // Objects identifying seat categories static final Object BUSINESS_CLASS = "BusinessClass"; static final Object ECONOMY_CLASS = "EconomyClass"; // Limits on capacity of this kind of Plane private static final int LEAST_SEATS = 8; private static final int MOST_SEATS = 50; private static final int DEFAULT_SEATS = 25; 17

18 // Initial costs for seat categories for this type Airplane. private static final java.util.map initialcosts = new java.util.hashmap(2); // Initialize that information when class is loaded. static { initialcosts.put(business_class, new Double(200.)); initialcosts.put(economy_class, new Double(150.)); public SmallPlane() { this(default_seats); public SmallPlane(int numseats) { // Base class will check that numseats is within range super(numseats, LEAST_SEATS, MOST_SEATS, initialcosts.keyset().iterator()); protected double getinitialcost(object category) { Double initialcost = (Double) initialcosts.get(category); if (initialcost!= null) return initialcost.doublevalue(); else throw new IllegalArgumentException( category + " not recognized for " + getclass().getname()); public String tostring() { return "Small" + super.tostring(); 18

19 Inheritance homework - Additional classes Virtually unchanged from earlier implementations version1/amount.java /** An encapsulation of an amount of currency public class Amount { private long amount; // currently maintained in whole cents public Amount(double d) { amount = (long) (d * 100); /** Converts from internal representation back to double. public double getasdouble() { return ((double) amount) / 100.; // Class (static) data to do a nice formatting job on amounts // when needed. private static java.text.numberformat formatter; private static final int fracdigits = 2; static { // This block of code is a "static initializer": it gets // executed once automatically when the class is loaded. You // use them when you need more initialization than you can // accomplish by just creating a new object and to avoid // having to have special Class.init() methods. formatter = java.text.numberformat.getcurrencyinstance(); formatter.setgroupingused(false); formatter.setmaximumfractiondigits(fracdigits); formatter.setminimumfractiondigits(fracdigits); // Private helper method private String formatamount() { String num = formatter.format(getasdouble()); return num; 19

20 public String tostring() { return formatamount(); Slight difference in the way Airplanes are constructed. version1/cmdlineairlinetest.java /** A class that will be used to test Airline and Airplane capabilities public class CmdLineAirlineTest { // Going to distribute airplanes between theseo airlines private String[] airlinenames = { "USAirways", "United", "AirFrance" ; private Airline[] sampleairlines; public void createairline(string[] types) { // Create a new Airlines sampleairlines = new Airline[airlineNames.length]; for (int i = 0; i < airlinenames.length; i++) { sampleairlines[i] = new Airline(airlineNames[i]); Airplane plane; for (int i = 0; i < types.length; i++) { // Request the Airline to add several new Airplanes // of the requested types String type = types[i]; if (type.touppercase().startswith("b")) plane = new BigPlane(); else if (type.touppercase().startswith("m")) plane = new MediumPlane(); else if (type.touppercase().startswith("s")) plane = new SmallPlane(); 20

21 else { throw new IllegalArgumentException( type + " not a recognized kind of Airplane"); // Assign the airplane to one of the Airlines Airline whichone = sampleairlines[i % sampleairlines.length]; whichone.addairplane(plane); public void changeairline() { // Cause the Airline objects to adjust their prices for (int i = 0; i < sampleairlines.length; i++) { sampleairlines[i].adjustprices( (i+1) *.1); // i0% increase public void identifyairline(java.io.printstream out) { // Cause the Airline object and the Airplane objects to // identify themselves and, in the case of the Airplanes, // their current cost per seat. for (int i = 0; i < sampleairlines.length; i++) { out.println( sampleairlines[i].tostring() ); public static void main(string[] args) { if ( args.length < 1 ) { System.out.println( "usage: CmdLineAirlineTest planetypes" + "\nwhere planetypes are big medium small"); else { CmdLineAirlineTest tester = new CmdLineAirlineTest(); tester.createairline(args); tester.changeairline(); tester.identifyairline(system.out); 21

22 Inheritance homework - A Problem Problem - Derived class specific constants. version1/airline.java public class Airline { /** The name for the airline */ String name; /** A collection of Airplanes */ java.util.arraylist airplanes = new java.util.arraylist(); /** Constructor name name of the airline public Airline(String name) { this.name = name; /** Add an airplane to the airlines s collection */ public void addairplane(airplane plane) { airplanes.add(plane); /** Adjust the prices of airplanes in the collection */ public void adjustprices(double percent) { for (int i = 0; i < airplanes.size(); i++) { Airplane plane = (Airplane) airplanes.get(i); double cost; // This kind of coding style is an indication that // polymorphism is not adequately supported by the // Airplane base class. // Here the problem is that the costs for each plane // class are tied to class specific constants. 22

23 if (plane instanceof BigPlane) { cost = plane.getcostperseat(bigplane.first_class); cost += (cost * percent); plane.updatecostperseat(bigplane.first_class, cost); cost = plane.getcostperseat(bigplane.business_class); cost += (cost * percent); plane.updatecostperseat(bigplane.business_class, cost); cost = plane.getcostperseat(bigplane.economy_class); cost += (cost * percent); plane.updatecostperseat(bigplane.economy_class, cost); else if (plane instanceof MediumPlane) { cost = plane.getcostperseat(mediumplane.first_class); cost += (cost * percent); plane.updatecostperseat(mediumplane.first_class, cost); cost = plane.getcostperseat(mediumplane.business_class); cost += (cost * percent); plane.updatecostperseat(mediumplane.business_class, cost); cost = plane.getcostperseat(mediumplane.economy_class); cost += (cost * percent); plane.updatecostperseat(mediumplane.economy_class, cost); else if (plane instanceof SmallPlane) { cost = plane.getcostperseat(smallplane.business_class); cost += (cost * percent); plane.updatecostperseat(smallplane.business_class, cost); cost = plane.getcostperseat(smallplane.economy_class); cost += (cost * percent); plane.updatecostperseat(smallplane.economy_class, cost); else { // And here s the real tip off that inheritance / // polymorphism isn t being used System.err.println("don t know how to adjust prices of " + plane.getclass().getname()); /** Provide identifying information for the airline 23

24 public String tostring() { StringBuffer buf = new StringBuffer("Airline:"); buf.append(name); for (int i = 0; i < airplanes.size(); i++) { buf.append("\nplane"); buf.append(i); buf.append(":"); buf.append(airplanes.get(i)); return buf.tostring(); Results in brittle client / consumer classes: objects that use Airplanes are forced to be aware of derived classes. Changes in the object hierarchy / addition of new derived classes will have ripple effects. Similar to some homework solutions that defined separate methods for each seat category. That breaks polymorphism. Does not meet the requirement that the Airline class should not have any knowledge of specific classes derived from Airplane. 24

25 Part of the answer: Type Safe Enumeration version3/seatcategory.java /** A simple typesafe enumeration of seat categories public class SeatCategory { private final String name; private SeatCategory(String name) { this.name = name; public String tostring() { return name; public static final SeatCategory FIRST_CLASS = new SeatCategory("First Class"); public static final SeatCategory BUSINESS_CLASS = new SeatCategory("Business Class"); public static final SeatCategory ECONOMY_CLASS = new SeatCategory("Economy Class"); 25

26 Abstract Base class The use of a type safe enumeration reduces the freedom of derived classes to define their own categories. version3/airplane.java import java.util.iterator; import java.util.set; import java.util.hashmap; /** A base class to encapsulate information need for an ** airplane: its identifier, the number of seats (total ** and currently available) and the current costs per ** seat. public abstract class Airplane { /** kkeps track of id number to be assigned next */ private static int nextid = 0; /** An identifying number for the airplane instance */ private String id; /** The total number of seats */ private int totalseats; /** The number of currently available (un-sold) seats */ private int availseats; /** The current cost for a seat in several categories */ private HashMap costsperseat = new HashMap(); // Each derived class has a minimum and and maximum number of seats private int lowrange; private int highrange; /** Create an airplane (from derived classes) seats initial capacity in seats low least seats plane will have high most seats plane will have IllegalArgumentException if numnber of seats exceeds range protected Airplane(int seats, int low, int high) { if (seats < low seats > high) { 26

27 throw new IllegalArgumentException( seats + " seats is out of range " + low + " - " + high); this.id = String.valueOf(++nextId); this.totalseats = seats; availseats = totalseats; this.lowrange = low; this.highrange = high; /** Set the cost per seat to a new amount for a category */ protected void setcostperseat(seatcategory category, double newcost) { Amount costpercategory = new Amount(newCost); costsperseat.put(category, costpercategory); /** Set the cost per seat to a new amount, but only for ** existing categories (and only from other classes in ** the same package. category seat class to update cost for newcost updated cost of SeatCategory seat IllegalArgumentException if category void updatecostperseat(seatcategory category, double newcost) { if (! costsperseat.containskey(category)) { throw new IllegalArgumentException( getclass().getname() + " does not have a seat category \"" + category + "\""); // Replace it Amount costpercategory = new Amount(newCost); costsperseat.put(category, costpercategory); /** Get the cost per seat for a specified SeatCategory */ protected double getcostperseat(seatcategory category) { Amount costforcategory = (Amount) costsperseat.get(category); if (costforcategory == null) { // someone asked for a category that doesn t exist throw new IllegalArgumentException( category + " seats don t exist for " + getclass().getname()); else return costforcategory.getasdouble(); /** Return the airplane s identifier as a String */ String getid() { 27

28 return id; // The platform specific end of line character: private static final String endl = System.getProperty("line.separator"); public String tostring() { StringBuffer buf = new StringBuffer("Airplane:"); buf.append(getid()); buf.append(" seats:"); buf.append(totalseats); buf.append(" avail:"); buf.append(availseats); Set keys = costsperseat.keyset(); for ( Iterator i = keys.iterator(); i.hasnext(); ) { Object key = i.next(); buf.append(endl); buf.append("\t"); buf.append(key); // calls tostring() on key (SeatCategory) buf.append(":"); double value = getcostperseat((seatcategory) key); buf.append(value); // calls tostring() on value (Amount) return buf.tostring(); 28

29 Derived classes version3/bigplane.java public class BigPlane extends Airplane { // Constants for initial, default seat costs private static final double INITIAL_FIRST_CLASS_COST = 500.; private static final double INITIAL_BUSINESS_CLASS_COST = 350.; private static final double INITIAL_ECONOMY_CLASS_COST = 200.; // Constants for allowable number of seats private static final int LEAST_SEATS = 200; private static final int MOST_SEATS = 300; private static final int DEFAULT_SEATS = 250; public BigPlane() { this(default_seats); public BigPlane(int numseats) { // Base class will check that numseats is within range super(numseats, LEAST_SEATS, MOST_SEATS); // Assign initial seat categories and costs setcostperseat(seatcategory.first_class, INITIAL_FIRST_CLASS_COST); setcostperseat(seatcategory.business_class, INITIAL_BUSINESS_CLASS_COST); setcostperseat(seatcategory.economy_class, INITIAL_ECONOMY_CLASS_COST); public String tostring() { return "Big" + super.tostring(); version3/mediumplane.java public class MediumPlane extends Airplane { // Constants for initial, default seat costs private static final double INITIAL_FIRST_CLASS_COST = 400.; private static final double INITIAL_BUSINESS_CLASS_COST = 200.; private static final double INITIAL_ECONOMY_CLASS_COST = 150.; // Constants for allowable number of seats 29

30 private static final int LEAST_SEATS = 50; private static final int MOST_SEATS = 200; private static final int DEFAULT_SEATS = 150; public MediumPlane() { this(default_seats); public MediumPlane(int numseats) { // Base class will check that numseats is within range super(numseats, LEAST_SEATS, MOST_SEATS); // Assign initial seat categories and costs setcostperseat(seatcategory.first_class, INITIAL_FIRST_CLASS_COST); setcostperseat(seatcategory.business_class, INITIAL_BUSINESS_CLASS_COST); setcostperseat(seatcategory.economy_class, INITIAL_ECONOMY_CLASS_COST); public String tostring() { return "Medium" + super.tostring(); version3/smallplane.java public class SmallPlane extends Airplane { // Constants for initial, default seat costs private static final double INITIAL_BUSINESS_CLASS_COST = 200.; private static final double INITIAL_ECONOMY_CLASS_COST = 150.; // Constants for allowable number of seats private static final int LEAST_SEATS = 8; private static final int MOST_SEATS = 50; private static final int DEFAULT_SEATS = 25; public SmallPlane() { this(default_seats); public SmallPlane(int numseats) { // Base class will check that numseats is within range super(numseats, LEAST_SEATS, MOST_SEATS); // Assign initial seat categories and costs setcostperseat(seatcategory.business_class, INITIAL_BUSINESS_CLASS_COST); setcostperseat(seatcategory.economy_class, INITIAL_ECONOMY_CLASS_COST); 30

31 public String tostring() { return "Small" + super.tostring(); 31

32 Client class uses polymorphic access version3/airline.java public class Airline { /** The name for the airline */ String name; /** A collection of Airplanes */ java.util.arraylist airplanes = new java.util.arraylist(); /** Constructor name name of the airline public Airline(String name) { this.name = name; /** Add an airplane to the airlines s collection */ public void addairplane(airplane plane) { airplanes.add(plane); /** Adjust the prices of airplanes in the collection */ public void adjustprices(double percent) { SeatCategory[] categories = { SeatCategory.FIRST_CLASS, SeatCategory.BUSINESS_CLASS, SeatCategory.ECONOMY_CLASS, ; for (int i = 0; i < airplanes.size(); i++) { Airplane plane = (Airplane) airplanes.get(i); double cost; for (int c = 0; c < categories.length; c++) { 32

33 SeatCategory category = categories[c]; try { cost = plane.getcostperseat(category); cost = cost + (cost * percent); plane.updatecostperseat(category, cost); catch (IllegalArgumentException e) { // We tried to change a category that doesn t exist // for this type of Airplane. /** Provide identifying information for the airline public String tostring() { StringBuffer buf = new StringBuffer("Airline:"); buf.append(name); for (int i = 0; i < airplanes.size(); i++) { buf.append("\nplane"); buf.append(i); buf.append(":"); buf.append(airplanes.get(i)); return buf.tostring(); 33

34 Improving the Type Safe Enumeration SeatCategory now provides a (private) Iterator implementation version4/seatcategory.java import java.util.iterator; /** A simple typesafe enumeration of seat categories public class SeatCategory { private final String name; private SeatCategory(String name) { this.name = name; public String tostring() { return name; public static final SeatCategory FIRST_CLASS = new SeatCategory("First Class"); public static final SeatCategory BUSINESS_CLASS = new SeatCategory("Business Class"); public static final SeatCategory ECONOMY_CLASS = new SeatCategory("Economy Class"); public static Iterator iterator() { SeatCategory[] categories = { FIRST_CLASS, BUSINESS_CLASS, ECONOMY_CLASS, 34

35 ; return new SeatCategoryIterator( categories ); class SeatCategoryIterator implements Iterator { SeatCategory[] categories; int next = 0; SeatCategoryIterator (SeatCategory[] categories) { this.categories = categories; public boolean hasnext() { return (next < categories.length); public Object next() { if (next >= categories.length) throw new java.util.nosuchelementexception(); else return categories[next++]; public void remove() { throw new UnsupportedOperationException(); 35

36 Client class is more independent version4/airline.java import java.util.iterator; public class Airline { /** The name for the airline */ String name; /** A collection of Airplanes */ java.util.list airplanes = new java.util.arraylist(); /** Constructor name name of the airline public Airline(String name) { this.name = name; /** Add an airplane to the airlines s collection */ public void addairplane(airplane plane) { airplanes.add(plane); /** Adjust the prices of airplanes in the collection */ public void adjustprices(double percent) { for (int i = 0; i < airplanes.size(); i++) { Airplane plane = (Airplane) airplanes.get(i); double cost; // Now Airline objects are independent of changes in // the kinds of SeatCategories that might be added // (although in a real situation, each Airline might // define its own SeatCategories and manage them.) for ( Iterator c = SeatCategory.iterator(); c.hasnext(); ) { SeatCategory category = (SeatCategory) c.next(); try { 36

37 cost = plane.getcostperseat(category); cost = cost + (cost * percent); plane.updatecostperseat(category, cost); catch (IllegalArgumentException e) { // We tried to change a category that doesn t exist // for this type of Airplane. /** Provide identifying information for the airline public String tostring() { StringBuffer buf = new StringBuffer("Airline:"); buf.append(name); for (int i = 0; i < airplanes.size(); i++) { buf.append("\nplane"); buf.append(i); buf.append(":"); buf.append(airplanes.get(i)); return buf.tostring(); 37

38 Homework Reading Chapter 9 - Formalizing Requirements through Use Cases Chapter 10 - Modeling the Static / Data Aspects of the System 38

Highlights of Last Week

Highlights of Last Week Highlights of Last Week Using Collection classes Marking methods protected to permit access only from derived classes Marking classes abstract to force inheritance Marking classes final to prevent inheritance

More information

Highlights of Last Week

Highlights of Last Week 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

More information

Highlights of Previous Lecture

Highlights of Previous Lecture Highlights of Previous Lecture Final Project Goals 1. Set up collections of Flights 2. Maintain information about reservation availability on flights 3. Respond to reservation requests 4. Set up collections

More information

Abstract Classes and Interfaces

Abstract Classes and Interfaces Abstract Classes and Interfaces Reading: Reges and Stepp: 9.5 9.6 CSC216: Programming Concepts Sarah Heckman 1 Abstract Classes A Java class that cannot be instantiated, but instead serves as a superclass

More information

Department of Civil and Environmental Engineering, Spring Semester, ENCE 688R: Final Exam: 2 Hours, Open Book and Open Notes

Department of Civil and Environmental Engineering, Spring Semester, ENCE 688R: Final Exam: 2 Hours, Open Book and Open Notes Department of Civil and Environmental Engineering, Spring Semester, 2017 ENCE 688R: Final Exam: 2 Hours, Open Book and Open Notes Name : Question Points Score 1 50 2 30 3 20 Total 100 1 Question 1: 50

More information

Homework 2: Imperative Due: 5:00 PM, Feb 15, 2019

Homework 2: Imperative Due: 5:00 PM, Feb 15, 2019 CS18 Integrated Introduction to Computer Science Fisler Homework 2: Imperative Due: 5:00 PM, Feb 15, 2019 Contents 1 Overview of Generic/Parameterized Types 2 2 Double the Fun with Doubly-Linked Lists

More information

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

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types

More information

MODULE 6q - Exceptions

MODULE 6q - Exceptions MODULE 6q - Exceptions THE TRY-CATCH CONSTRUCT Three different exceptions are referred to in the program below. They are the ArrayIndexOutOfBoundsException which is built-into Java and two others, BadLuckException

More information

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11 Administration Exceptions CS 99 Summer 2000 Michael Clarkson Lecture 11 Lab 10 due tomorrow No lab tomorrow Work on final projects Remaining office hours Rick: today 2-3 Michael: Thursday 10-noon, Monday

More information

Builder pattern. A creational pattern

Builder pattern. A creational pattern Builder pattern A creational pattern Building a complex object Let s say that we have a class for pretty complex objects, with lots of internal instance variables. We could provide a lot of constructors

More information

Lesson 10B Class Design. By John B. Owen All rights reserved 2011, revised 2014

Lesson 10B Class Design. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10B Class Design By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Encapsulation Inheritance and Composition is a vs has a Polymorphism Information Hiding Public

More information

Java Magistère BFA

Java Magistère BFA Java 101 - Magistère BFA Lesson 3: Object Oriented Programming in Java Stéphane Airiau Université Paris-Dauphine Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 1 Goal : Thou Shalt

More information

Within a source file or class we find the typical layout of file MyClass.java : [/* * header comment, for CVS, IP issues, etc. */] [package foo;]

Within a source file or class we find the typical layout of file MyClass.java : [/* * header comment, for CVS, IP issues, etc. */] [package foo;] Producing Production Quality Software Lecture 9: System Design in Java Prof. Arthur P. Goldberg Fall, 2005 Small scale Within a source file or class we find the typical layout of file MyClass.java : [/*

More information

6.005 Elements of Software Construction Fall 2008

6.005 Elements of Software Construction Fall 2008 MIT OpenCourseWare http://ocw.mit.edu 6.005 Elements of Software Construction Fall 2008 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. 6.005 elements

More information

Java for Interfaces and Networks (DT3010, HT11)

Java for Interfaces and Networks (DT3010, HT11) Java for Interfaces and Networks (DT3010, HT11) Networking with Threads and Federico Pecora School of Science and Technology Örebro University federico.pecora@oru.se Federico Pecora Java for Interfaces

More information

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

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

CSE 70 Final Exam Fall 2009

CSE 70 Final Exam Fall 2009 Signature cs70f Name Student ID CSE 70 Final Exam Fall 2009 Page 1 (10 points) Page 2 (16 points) Page 3 (22 points) Page 4 (13 points) Page 5 (15 points) Page 6 (20 points) Page 7 (9 points) Page 8 (15

More information

CMSC 132, Object-Oriented Programming II Summer Lecture 9:

CMSC 132, Object-Oriented Programming II Summer Lecture 9: CMSC 132, Object-Oriented Programming II Summer 2018 Lecturer: Anwar Mamat Lecture 9: Disclaimer: These notes may be distributed outside this class only with the permission of the Instructor. 9.1 QUEUE

More information

CS1004: Intro to CS in Java, Spring 2005

CS1004: Intro to CS in Java, Spring 2005 CS1004: Intro to CS in Java, Spring 2005 Lecture #23: OO Design, cont d. Janak J Parekh janak@cs.columbia.edu Administrivia HW#5 due Tuesday And if you re cheating on (or letting others see your) HW#5

More information

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch Problem Solving Creating a class from scratch 1 Recipe for Writing a Class 1. Write the class boilerplate stuff 2. Declare Fields 3. Write Creator(s) 4. Write accessor methods 5. Write mutator methods

More information

PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 10. PUTTING IT ALL TOGETHER. Are we there yet?

PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 10. PUTTING IT ALL TOGETHER. Are we there yet? PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 10. PUTTING IT ALL TOGETHER Are we there yet? Developing software, OOA&D style You ve got a lot of new tools, techniques, and ideas about how to develop

More information

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide AP Computer Science Chapter 10 Implementing and Using Classes Study Guide 1. A class that uses a given class X is called a client of X. 2. Private features of a class can be directly accessed only within

More information

MORE OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 4 09/01/2011

MORE OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 4 09/01/2011 MORE OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 4 09/01/2011 1 Goals of the Lecture Continue a review of fundamental object-oriented concepts 2 Overview of OO Fundamentals

More information

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws 1 By the end of this lecture, you will be able to differentiate between errors, exceptions,

More information

Java for Interfaces and Networks (DT3029)

Java for Interfaces and Networks (DT3029) Java for Interfaces and Networks (DT3029) Lecture 4 Networking with Threads and Containers Federico Pecora federico.pecora@oru.se Center for Applied Autonomous Sensor Systems (AASS) Örebro University,

More information

Classes Classes 2 / 36

Classes Classes 2 / 36 Classes 1 / 36 Classes Classes 2 / 36 Anatomy of a Class By the end of next lecture, you ll understand everything in this class definition. package edu. gatech. cs1331. card ; import java. util. Arrays

More information

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

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are built on top of that. CMSC131 Inheritance Object When we talked about Object, I mentioned that all Java classes are "built" on top of that. This came up when talking about the Java standard equals operator: boolean equals(object

More information

More OO Fundamentals. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 4 09/11/2012

More OO Fundamentals. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 4 09/11/2012 More OO Fundamentals CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 4 09/11/2012 1 Goals of the Lecture Continue a review of fundamental object-oriented concepts 2 Overview of OO Fundamentals

More information

Another IS-A Relationship

Another IS-A Relationship Another IS-A Relationship Not all classes share a vertical relationship. Instead, some are supposed to perform the specific methods without a vertical relationship. Consider the class Bird inherited from

More information

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

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000 The Object Class Mark Allen Weiss Copyright 2000 1/4/02 1 java.lang.object All classes either extend Object directly or indirectly. Makes it easier to write generic algorithms and data structures Makes

More information

Implementation. (Mapping to Java) Jörg Kienzle & Alfred Strohmeier. COMP-533 Implementation

Implementation. (Mapping to Java) Jörg Kienzle & Alfred Strohmeier. COMP-533 Implementation Implementation (Mapping to Java) Jörg Kienzle & Alfred Strohmeier COMP-533 Implementation Datatype Enumeration Class Attribute Association Inheritance Method Visibility Collections Overview 2 Data Type

More information

CN208 Introduction to Computer Programming

CN208 Introduction to Computer Programming CN208 Introduction to Computer Programming Lecture #11 Streams (Continued) Pimarn Apipattanamontre Email: pimarn@pimarn.com 1 The Object Class The Object class is the direct or indirect superclass of every

More information

Wrapper Classes double pi = new Double(3.14); 3 double pi = new Double("3.14"); 4... Zheng-Liang Lu Java Programming 290 / 321

Wrapper Classes double pi = new Double(3.14); 3 double pi = new Double(3.14); 4... Zheng-Liang Lu Java Programming 290 / 321 Wrapper Classes To treat values as objects, Java supplies standard wrapper classes for each primitive type. For example, you can construct a wrapper object from a primitive value or from a string representation

More information

Exploring the Java API, Packages & Collections

Exploring the Java API, Packages & Collections 6.092 - Introduction to Software Engineering in Java Lecture 7: Exploring the Java API, Packages & Collections Tuesday, January 29 IAP 2008 Cite as: Evan Jones, Olivier Koch, and Usman Akeju, course materials

More information

G51PGP Programming Paradigms. Lecture OO-4 Aggregation

G51PGP Programming Paradigms. Lecture OO-4 Aggregation G51PGP Programming Paradigms Lecture OO-4 Aggregation 1 The story so far We saw that C code can be converted into Java code Note real object oriented code though Hopefully shows you how much you already

More information

PASS4TEST IT 인증시험덤프전문사이트

PASS4TEST IT 인증시험덤프전문사이트 PASS4TEST IT 인증시험덤프전문사이트 http://www.pass4test.net 일년동안무료업데이트 Exam : 1z0-809 Title : Java SE 8 Programmer II Vendor : Oracle Version : DEMO Get Latest & Valid 1z0-809 Exam's Question and Answers 1 from

More information

EINDHOVEN UNIVERSITY OF TECHNOLOGY

EINDHOVEN UNIVERSITY OF TECHNOLOGY EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics & Computer Science Exam Programming Methods, 2IP15, Wednesday 17 April 2013, 09:00 12:00 TU/e THIS IS THE EXAMINER S COPY WITH (POSSIBLY INCOMPLETE)

More information

Tiers (or layers) Separation of concerns

Tiers (or layers) Separation of concerns Tiers (or layers) Separation of concerns Hiding the type of storage from the client class Let s say we have a program that needs to fetch objects from a storage. Should the program have to be concerned

More information

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

F I N A L E X A M I N A T I O N Faculty Of Computer Studies M257 Putting Java to Work F I N A L E X A M I N A T I O N Number of Exam Pages: (including this cover sheet( Spring 2011 April 4, 2011 ( 5 ) Time Allowed: ( 1.5 ) Hours Student

More information

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Lecture 36: Cloning Last time: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Today: 1. Project #7 assigned 2. equals reconsidered 3. Copying and cloning 4. Composition 11/27/2006

More information

PROGRAMMING III OOP. JAVA LANGUAGE COURSE

PROGRAMMING III OOP. JAVA LANGUAGE COURSE COURSE 3 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Classes Objects Object class Acess control specifier fields methods classes COUSE CONTENT Inheritance Abstract classes Interfaces instanceof

More information

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

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University Day 3 COMP 1006/1406A Summer 2016 M. Jason Hinek Carleton University today s agenda assignments 1 was due before class 2 is posted (be sure to read early!) a quick look back testing test cases for arrays

More information

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

CSCI 136 Written Exam #0 Fundamentals of Computer Science II Spring 2015 CSCI 136 Written Exam #0 Fundamentals of Computer Science II Spring 2015 Name: This exam consists of 6 problems on the following 7 pages. You may use your single-sided handwritten 8 ½ x 11 note sheet during

More information

PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 00. WELCOME TO OBJECTVILLE. Speaking the Language of OO

PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 00. WELCOME TO OBJECTVILLE. Speaking the Language of OO PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 00. WELCOME TO OBJECTVILLE Speaking the Language of OO COURSE INFO Instructor : Alper Bilge TA : Gökhan Çıplak-Ahmet Alkılınç Time : Tuesdays 2-5pm Location

More information

CS1004: Intro to CS in Java, Spring 2005

CS1004: Intro to CS in Java, Spring 2005 CS1004: Intro to CS in Java, Spring 2005 Lecture #13: Java OO cont d. Janak J Parekh janak@cs.columbia.edu Administrivia Homework due next week Problem #2 revisited Constructors, revisited Remember: a

More information

WES-CS GROUP MEETING #9

WES-CS GROUP MEETING #9 WES-CS GROUP MEETING #9 Exercise 1: Practice Multiple-Choice Questions 1. What is output when the following code executes? String S1 = new String("hello"); String S2 = S1 +! ; S1 = S1 + S1; System.out.println(S1);

More information

Selected Java Topics

Selected Java Topics Selected Java Topics Introduction Basic Types, Objects and Pointers Modifiers Abstract Classes and Interfaces Exceptions and Runtime Exceptions Static Variables and Static Methods Type Safe Constants Swings

More information

Timing for Interfaces and Abstract Classes

Timing for Interfaces and Abstract Classes Timing for Interfaces and Abstract Classes Consider using abstract classes if you want to: share code among several closely related classes declare non-static or non-final fields Consider using interfaces

More information

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle Boggle If you are not familiar with the game Boggle, the game is played with 16 dice that have letters on all faces. The dice are randomly deposited into a four-by-four grid so that the players see the

More information

Announcements/Follow-ups

Announcements/Follow-ups Announcements/Follow-ups Midterm #2 Friday Everything up to and including today Review section tomorrow Study set # 6 online answers posted later today P5 due next Tuesday A good way to study Style omit

More information

Remedial Java - Excep0ons 3/09/17. (remedial) Java. Jars. Anastasia Bezerianos 1

Remedial Java - Excep0ons 3/09/17. (remedial) Java. Jars. Anastasia Bezerianos 1 (remedial) Java anastasia.bezerianos@lri.fr Jars Anastasia Bezerianos 1 Disk organiza0on of Packages! Packages are just directories! For example! class3.inheritancerpg is located in! \remedialjava\src\class3\inheritencerpg!

More information

COMP-202. Objects, Part III. COMP Objects Part III, 2013 Jörg Kienzle and others

COMP-202. Objects, Part III. COMP Objects Part III, 2013 Jörg Kienzle and others COMP-202 Objects, Part III Lecture Outline Static Member Variables Parameter Passing Scopes Encapsulation Overloaded Methods Foundations of Object-Orientation 2 Static Member Variables So far, member variables

More information

Object Oriented Design. Object-Oriented Design. Inheritance & Polymorphism. Class Hierarchy. Goals Robustness Adaptability Flexible code reuse

Object Oriented Design. Object-Oriented Design. Inheritance & Polymorphism. Class Hierarchy. Goals Robustness Adaptability Flexible code reuse Object-Oriented Design Object Oriented Design Goals Robustness Adaptability Flexible code reuse Principles Abstraction Encapsulation Modularity March 2005 Object Oriented Design 1 March 2005 Object Oriented

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 26 March 23, 2016 Inheritance and Dynamic Dispatch Chapter 24 Inheritance Example public class { private int x; public () { x = 0; } public void incby(int

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information

Introduction to Software Engineering in Java. Exceptions, I/O, and you++

Introduction to Software Engineering in Java. Exceptions, I/O, and you++ 6.092 - Introduction to Software Engineering in Java Lecture 8: Exceptions, I/O, and you++ Thursday, January 31 IAP 2008 Cite as: Evan Jones, Olivier Koch, and Usman Akeju, course materials for 6.092 Introduction

More information

Lecture 17: Implementing HashTables 10:00 AM, Mar 5, 2018

Lecture 17: Implementing HashTables 10:00 AM, Mar 5, 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Contents Lecture 17: Implementing HashTables 10:00 AM, Mar 5, 2018 1 Implementing Hashtables 1 1.1 Understanding Collisions..................................

More information

Interview Questions I received in 2017 and 2018

Interview Questions I received in 2017 and 2018 Interview Questions I received in 2017 and 2018 Table of Contents INTERVIEW QUESTIONS I RECEIVED IN 2017 AND 2018... 1 1 OOPS... 3 1. What is the difference between Abstract and Interface in Java8?...

More information

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

Computer Science II (20073) Week 1: Review and Inheritance Computer Science II 4003-232-01 (20073) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Hardware and Software Hardware Physical devices in a computer system

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 15 Lecture 15-1: Implementing ArrayIntList reading: 15.1-15.3 Recall: classes and objects class: A program entity that represents: A complete program or module, or A template

More information

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes 1 CS257 Computer Science II Kevin Sahr, PhD Lecture 5: Writing Object Classes Object Class 2 objects are the basic building blocks of programs in Object Oriented Programming (OOP) languages objects consist

More information

CMPSCI 187: Programming With Data Structures. Lecture #21: Array-Based Lists David Mix Barrington 26 October 2012

CMPSCI 187: Programming With Data Structures. Lecture #21: Array-Based Lists David Mix Barrington 26 October 2012 CMPSCI 187: Programming With Data Structures Lecture #21: Array-Based Lists David Mix Barrington 26 October 2012 Array-Based Lists Comparing Objects: equals and Comparable Lists: Unsorted, Sorted, and

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007 Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007 Java We will be programming in Java in this course. Partly because it is a reasonable language, and partly because you

More information

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes. a and Interfaces Class Shape Hierarchy Consider the following class hierarchy Shape Circle Square Problem AND Requirements Suppose that in order to exploit polymorphism, we specify that 2-D objects must

More information

Introduction: Abstract Data Types and Java Review

Introduction: Abstract Data Types and Java Review Introduction: Abstract Data Types and Java Review Computer Science E-22 Harvard Extension School David G. Sullivan, Ph.D. Welcome to Computer Science E-22! We will study fundamental data structures. ways

More information

The class Object. Lecture CS1122 Summer 2008

The class Object.  Lecture CS1122 Summer 2008 The class Object http://www.javaworld.com/javaworld/jw-01-1999/jw-01-object.html Lecture 10 -- CS1122 Summer 2008 Review Object is at the top of every hierarchy. Every class in Java has an IS-A relationship

More information

Inheritance (Part 5) Odds and ends

Inheritance (Part 5) Odds and ends Inheritance (Part 5) Odds and ends 1 Static Methods and Inheritance there is a significant difference between calling a static method and calling a non-static method when dealing with inheritance there

More information

Object-Oriented Design. March 2005 Object Oriented Design 1

Object-Oriented Design. March 2005 Object Oriented Design 1 Object-Oriented Design March 2005 Object Oriented Design 1 Object Oriented Design Goals Robustness Adaptability Flexible code reuse Principles Abstraction Encapsulation Modularity March 2005 Object Oriented

More information

Topic 3 Encapsulation - Implementing Classes

Topic 3 Encapsulation - Implementing Classes Topic 3 Encapsulation - Implementing Classes And so, from Europe, we get things such as... object-oriented analysis and design (a clever way of breaking up software programming instructions and data into

More information

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions. Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions...catch...finally throw and throws By the end of this lecture, you will be able to differentiate between errors, exceptions, and

More information

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

Language Features. 1. The primitive types int, double, and boolean are part of the AP Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are

More information

CS61BL. Lecture 1: Welcome to CS61BL! Intro to Java and OOP Testing Error-handling

CS61BL. Lecture 1: Welcome to CS61BL! Intro to Java and OOP Testing Error-handling CS61BL Lecture 1: Welcome to CS61BL! Intro to Java and OOP Testing Error-handling About me Name: Edwin Liao Email: edliao@berkeley.edu Office hours: Thursday 3pm - 5pm Friday 11am - 1pm 611 Soda Or by

More information

Java exercises January François de Coligny, Nicolas Beudez

Java exercises January François de Coligny, Nicolas Beudez Java exercises January 2018 - François de Coligny, Nicolas Beudez 0. Preliminary Create a directory called java/ on your machine to host all exercises. 1. Create a Training application package training;

More information

COE318 Lecture Notes Week 10 (Nov 7, 2011)

COE318 Lecture Notes Week 10 (Nov 7, 2011) COE318 Software Systems Lecture Notes: Week 10 1 of 5 COE318 Lecture Notes Week 10 (Nov 7, 2011) Topics More about exceptions References Head First Java: Chapter 11 (Risky Behavior) The Java Tutorial:

More information

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Autumn /20/ Hal Perkins & UW CSE H-1

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Autumn /20/ Hal Perkins & UW CSE H-1 CSE P 501 Compilers Implementing ASTs (in Java) Hal Perkins Autumn 2009 10/20/2009 2002-09 Hal Perkins & UW CSE H-1 Agenda Representing ASTs as Java objects Parser actions Operations on ASTs Modularity

More information

Interfaces. James Brucker

Interfaces. James Brucker Interfaces James Brucker What is an Interface? An interface is a specification of (1) a required behavior any class that claims to "implement" the interface must perform the behavior (2) constant data

More information

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects CmSc 150 Fundamentals of Computing I Lesson 28: Introduction to Classes and Objects in Java 1. Classes and Objects True object-oriented programming is based on defining classes that represent objects with

More information

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2) Summary: Chapters 1 to 10 Sharma Chakravarthy Information Technology Laboratory (IT Lab) Computer Science and Engineering Department The University of Texas at Arlington, Arlington, TX 76019 Email: sharma@cse.uta.edu

More information

Arrays. Chapter Arrays What is an Array?

Arrays. Chapter Arrays What is an Array? Chapter 8 Arrays 81 Arrays 811 What is an Array? To motivate why we might be interested in using arrays, let us implement an app that creates a collection of doubles We will keep track of the number of

More information

CS 1331 Exam 1 ANSWER KEY

CS 1331 Exam 1 ANSWER KEY CS 1331 Exam 1 Fall 2016 ANSWER KEY Failure to properly fill in the information on this page will result in a deduction of up to 5 points from your exam score. Signing signifies you are aware of and in

More information

Course Status Polymorphism Containers Exceptions Midterm Review. CS Java. Introduction to Java. Andy Mroczkowski

Course Status Polymorphism Containers Exceptions Midterm Review. CS Java. Introduction to Java. Andy Mroczkowski CS 190 - Java Introduction to Java Andy Mroczkowski uamroczk@cs.drexel.edu Department of Computer Science Drexel University February 11, 2008 / Lecture 4 Outline Course Status Course Information & Schedule

More information

CS61B Lecture #12. Programming Contest: Coming up Saturday 5 October. See the contest announcement page, here.

CS61B Lecture #12. Programming Contest: Coming up Saturday 5 October. See the contest announcement page, here. CS61B Lecture #12 Programming Contest: Coming up Saturday 5 October. See the contest announcement page, here. Lateness: Yes, the lateness policy does extend to Project 0. Test 1: still scheduled for 16

More information

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

Java Classes. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar Java Classes Introduction to the Java Programming Language Produced by Eamonn de Leastar edeleastar@wit.ie Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. CMSC 131: Chapter 28 Final Review: What you learned this semester The Big Picture Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. Java

More information

COMP 250 Winter 2011 Reading: Java background January 5, 2011

COMP 250 Winter 2011 Reading: Java background January 5, 2011 Almost all of you have taken COMP 202 or equivalent, so I am assuming that you are familiar with the basic techniques and definitions of Java covered in that course. Those of you who have not taken a COMP

More information

Data Structures Brett Bernstein

Data Structures Brett Bernstein Data Structures Brett Bernstein Lecture 8: Iterators, Maps, and Hashtables Exercises 1. Show how to print out the elements of a doubly linked list in reverse order. 2. What are the Java API classes that

More information

Class Libraries. Readings and References. Java fundamentals. Java class libraries and data structures. Reading. Other References

Class Libraries. Readings and References. Java fundamentals. Java class libraries and data structures. Reading. Other References Reading Readings and References Class Libraries CSE 142, Summer 2002 Computer Programming 1 Other References» The Java tutorial» http://java.sun.com/docs/books/tutorial/ http://www.cs.washington.edu/education/courses/142/02su/

More information

CSE Summer Assignment #2

CSE Summer Assignment #2 CSE2011 - Summer 2016 - Assignment #2 Due Date: 28 th of June 2014 at 1:00PM NOTES You may work in groups of up to 3 and make one common submission (if more than one partner submits, it causes us delays

More information

Classes Classes 2 / 35

Classes Classes 2 / 35 Classes 1 / 35 Classes Classes 2 / 35 Anatomy of a Class By the end of next lecture, you ll understand everything in this class definition. package edu. gatech. cs1331. card ; import java. util. Arrays

More information

CSE 331 Summer 2017 Final Exam. The exam is closed book and closed electronics. One page of notes is allowed.

CSE 331 Summer 2017 Final Exam. The exam is closed book and closed electronics. One page of notes is allowed. Name Solution The exam is closed book and closed electronics. One page of notes is allowed. The exam has 6 regular problems and 1 bonus problem. Only the regular problems will count toward your final exam

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, ,

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , CSE 143 Lecture 26 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, 15.3-15.4, 16.4-16.5 slides created by Marty Stepp, adapted by Alyssa Harding

More information

CS Week 14. Jim Williams, PhD

CS Week 14. Jim Williams, PhD CS 200 - Week 14 Jim Williams, PhD This Week 1. Final Exam: Conflict Alternatives Emailed 2. Team Lab: Object Oriented Space Game 3. BP2 Milestone 3: Strategy 4. Lecture: More Classes and Additional Topics

More information

1.Which four options describe the correct default values for array elements of the types indicated?

1.Which four options describe the correct default values for array elements of the types indicated? 1.Which four options describe the correct default values for array elements of the types indicated? 1. int -> 0 2. String -> "null" 3. Dog -> null 4. char -> '\u0000' 5. float -> 0.0f 6. boolean -> true

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 05.2 GOOD DESIGN = FLEXIBLE SOFTWARE. Give Your Software a 30-minute Workout

PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 05.2 GOOD DESIGN = FLEXIBLE SOFTWARE. Give Your Software a 30-minute Workout PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 05.2 GOOD DESIGN = FLEXIBLE SOFTWARE Give Your Software a 30-minute Workout previously on bim 209 Rick s Guitars is expanding previously on bim 209 3

More information

Outline. Object Oriented Programming. Course goals. Staff. Course resources. Assignments. Course organization Introduction Java overview Autumn 2003

Outline. Object Oriented Programming. Course goals. Staff. Course resources. Assignments. Course organization Introduction Java overview Autumn 2003 Outline Object Oriented Programming Autumn 2003 2 Course goals Software design vs hacking Abstractions vs language (syntax) Java used to illustrate concepts NOT a course about Java Prerequisites knowledge

More information

Design to interfaces. Favor composition over inheritance Find what varies and encapsulate it

Design to interfaces. Favor composition over inheritance Find what varies and encapsulate it Design Patterns The Gang of Four suggests a few strategies for creating good o-o designs, including Façade Design to interfaces. Favor composition over inheritance Find what varies and encapsulate it One

More information