Upload
erin-burke
View
212
Download
0
Embed Size (px)
Citation preview
Review of OOP in JavaReview of OOP in Java
What you should already know….What you should already know….(Appendices C, D, and E)(Appendices C, D, and E)
OutlineOutline
EncapsulationEncapsulation Inheritance & PolymorphismInheritance & Polymorphism
GUI as an example of I & PGUI as an example of I & P
ExceptionsExceptions
EncapsulationEncapsulation
Classes and objects: Classes and objects: reference and co-referencereference and co-reference data and operationsdata and operations
Methods and constructorsMethods and constructors arguments and parametersarguments and parameters overloadingoverloading javadoc commentsjavadoc comments
Static fields and methodsStatic fields and methods
Classes and ObjectsClasses and Objects
Class Class encapsulatesencapsulates data and operations data and operations keeps them together in one placekeeps them together in one placeString name = “Mark Young”;String name = “Mark Young”; // data// dataint len = name.length();int len = name.length(); // 10// 10int space = name.indexOf(“ ”);int space = name.indexOf(“ ”); // 4 (// 4 (sicsic))String city = “Wolfville”;String city = “Wolfville”; // more data// more dataString animal = city.substring(0,4);String animal = city.substring(0,4); // “Wolf”// “Wolf”
Class: StringClass: String objects: “Mark Young”, “Wolfville”, “Wolf”objects: “Mark Young”, “Wolfville”, “Wolf”
» object object variablesvariables: name, city, animal: name, city, animal
Classes, Objects and VariablesClasses, Objects and Variables
Class is a Class is a kindkind of thing; a of thing; a data typedata type the kind of data and the available operationsthe kind of data and the available operations
Object is an Object is an instanceinstance of the class; of the class; something a variable can something a variable can refer torefer to variables variables referrefer to, or to, or pointpoint to, objects to, objects
&name: “Mark Young”
&city: “Wolfville”
&animal: “Wolf”
String variables String objects String operations
get lengthfind index ofget substring…
Reference and Co-ReferenceReference and Co-Reference
Two variables can refer to the same objectTwo variables can refer to the same objectCar myCar = new Car(blue);Car myCar = new Car(blue); // data// dataCar disCar = myCar;Car disCar = myCar; // same // same objectobjectCar steves = new Car(blue);Car steves = new Car(blue); // same // same datadatadisCar.setColor(green);disCar.setColor(green); // // myCarmyCar is now green is now green
&myCar:
&disCar:
&stevesCar:
Car variables Car objects Car operations
…get colourchange colour…
DataData
What we know about objects of this classWhat we know about objects of this class class says what type it isclass says what type it is object holds informationobject holds information
Class Name: CarData:
make: (String)model: (String)year: (int)fuel (l): (double)mileage (km):
(double)colour: (Color)
Operations:…
make: Toyotamodel: Corollayear: 2009fuel (l): 23.7mileage (km): 164054.0colour: RED
myCar
Data DeclarationData Declaration
Data saved in Data saved in instance variablesinstance variables variables declared in the classvariables declared in the class access level (usually private, unless final)access level (usually private, unless final) if final (never going to change)if final (never going to change) data type (int, double, String, Color, …)data type (int, double, String, Color, …) namenamepublic final String MAKE, MODEL;public final String MAKE, MODEL;public final int YEAR;public final int YEAR;private double fuel, mileage;private double fuel, mileage;private Color colour;private Color colour;
Why Private? Why Public?Why Private? Why Public?
IVs are made private to keep clients from IVs are made private to keep clients from messing them upmessing them up accidentally or maliciouslyaccidentally or maliciously not allowed to say not allowed to say myCar.mileage = 10035.5;myCar.mileage = 10035.5;
» error: mileage is PRIVATE!error: mileage is PRIVATE!
Final variables can’t get messed upFinal variables can’t get messed up given value when object created; never changesgiven value when object created; never changes not allowed to say not allowed to say myCar.YEAR = 2013;myCar.YEAR = 2013;
» error: YEAR is FINAL!error: YEAR is FINAL!
OperationsOperations
What we can do with objects of this classWhat we can do with objects of this class class says what’s availableclass says what’s available object carries out actionsobject carries out actions
Class Name: CarData:
…Operations:
get mileagedrive some distanceadd fuelget colourchange colour…
make: Toyotamodel: Corollayear: 2009fuel (l): 23.7mileage (km): 164054.0colour: RED
myCarmake: Toyotamodel: Corollayear: 2009fuel (l): 17.4mileage (km): 164150.3colour: RED
myCar
myCar, drive 96.3 km.
MethodsMethods
In OOP, operations become methodsIn OOP, operations become methods length operation length operation length method length method change colour operation change colour operation setColor method setColor method
Methods addressed to objectsMethods addressed to objects usually thru a variable…usually thru a variable… name.length()name.length(),, myCar.drive(96.3) myCar.drive(96.3), …, … ……but not necessarily!but not necessarily! ““Hello”.length()Hello”.length(),, Math.pow(10, 3) Math.pow(10, 3), …, … ““calling the method”calling the method”
Method Header/InterfaceMethod Header/Interface
First line of method definitionFirst line of method definition access level (operations public, helpers private)access level (operations public, helpers private) if static (shared by whole class)if static (shared by whole class) void void oror return type (int, double, String[], …) return type (int, double, String[], …) method namemethod name parameter listparameter listpublic public void void setColor (Color c) setColor (Color c)public public Color Color getColor () getColor ()public static double pow (double base, double exponent)public static double pow (double base, double exponent)
Parameters/ArgumentsParameters/Arguments
Parameters are variablesParameters are variables data type and namedata type and name (double base, double exponent)(double base, double exponent), , (int n)(int n),, (Color c)(Color c), …, …
Arguments are valuesArguments are values of the correct typeof the correct type
» int num = 10;int num = 10; (10.5, 3.14)(10.5, 3.14), , (num)(num), , (new Color(0, 255, 0))(new Color(0, 255, 0)), …, …
Method call sets parameters to argumentsMethod call sets parameters to arguments basebase = = 10.510.5; ; exponentexponent = = 3.143.14
Getters and SettersGetters and Setters
Methods to get some part of object’s dataMethods to get some part of object’s data getter: getter: getMileagegetMileage, , getFuelgetFuel, , getColorgetColor, …, …
» most (non-final) IVs will have gettersmost (non-final) IVs will have getters
Methods to change some part of dataMethods to change some part of data setter: setter: setColorsetColor
» no setters for final instance variablesno setters for final instance variables» no setters for fuel and mileageno setters for fuel and mileage
• but but addFueladdFuel and and drivedrive will change them (“mutaters”) will change them (“mutaters”)
““immutable” objects have no setters at all!immutable” objects have no setters at all!
Referring to IVsReferring to IVs
Method definitions can refer to instance Method definitions can refer to instance variables by name in any methodvariables by name in any methodmileage += distance;mileage += distance;return colour;return colour; but to emphasize that it’s but to emphasize that it’s thisthis object’s data: object’s data:this.mileage += distance;this.mileage += distance;return this.colour;return this.colour;
» useful when a parameter has the same name:useful when a parameter has the same name:public void setColor(Color colour) {public void setColor(Color colour) { this.colour = colour;this.colour = colour; // // IVIV colour set to colour set to parameterparameter colour colour}}
Private MethodsPrivate Methods
Methods can be declared privateMethods can be declared private client can’t use these methodsclient can’t use these methods
» so not for the class operationsso not for the class operations they can only be called from inside this classthey can only be called from inside this class
» only to “help” this class carry out its operationsonly to “help” this class carry out its operations public methods should check their parameterspublic methods should check their parameters
» to make sure they make senseto make sure they make sense private methods can assume they’re OKprivate methods can assume they’re OK
» if they’re not, then we need to fix if they’re not, then we need to fix ourour code code
OverloadingOverloading
Methods in same class can share namesMethods in same class can share names called “overloading” the method (name)called “overloading” the method (name) must have different parameter listsmust have different parameter lists
» different different numbernumber of parameters of parameters» or different or different typestypes of parameters of parameters
related/similar operationsrelated/similar operationspublic double addFuelpublic double addFuel(double x)(double x) { … } … { … } …
» add given number of litres of fueladd given number of litres of fuelpublic double addFuelpublic double addFuel()() { … } { … }
» fill the tankfill the tank
ConstructorsConstructors
Put the initial information into the objectPut the initial information into the object use “new” commanduse “new” command give required datagive required data assign to a variable (assign to a variable (usuusu.).)Car myCar = new Car(Car myCar = new Car(
“Toyota”,“Toyota”,“Corolla”,“Corolla”,2009,2009,Color.RED);Color.RED);
» fuel and mileage start at 0.0fuel and mileage start at 0.0
/
myCarmake: /model: /year: 0fuel (l): 0.0mileage (km): 0.0colour: /
myCarmake: Toyotamodel: Corollayear: 2009fuel (l): 0.0mileage (km): 0.0colour: RED
myCar
Constructor DefinitionConstructor Definition
Different from method definitionsDifferent from method definitions access access usuallyusually public (but can be private, …) public (but can be private, …) nevernever static static no void/return type at allno void/return type at all name is same as name of classname is same as name of classpublic class Car {public class Car {public Car(String make, String model, int year, Color c) {public Car(String make, String model, int year, Color c) {
……}}
Constructor PurposeConstructor Purpose
Make sure every instance variable gets a Make sure every instance variable gets a reasonable valuereasonable value what the client asks for it to be, if possiblewhat the client asks for it to be, if possible some reasonable default if client doesn’t saysome reasonable default if client doesn’t say
» may depend on may depend on what else what else client asks forclient asks for
Constructor is only place where a Constructor is only place where a finalfinal variable can be given a valuevariable can be given a value
Overloaded ConstructorsOverloaded Constructors
Like overloaded methods, must have Like overloaded methods, must have different parameter listsdifferent parameter listspublic Car(String make, String model, int year, Color c)public Car(String make, String model, int year, Color c)public Car(int year, String make, String model, Color c)public Car(int year, String make, String model, Color c)public Car(String make, String model, int year)public Car(String make, String model, int year)public Car(int year, String make, String model)public Car(int year, String make, String model)public Car(Color c)public Car(Color c)
Primary ConstructorPrimary Constructor
Generally pick one constructor as primaryGenerally pick one constructor as primary it makes sure every IV gets a good valueit makes sure every IV gets a good value
Other constructors call the primary: Other constructors call the primary: this(…)this(…) add in arguments for missing parametersadd in arguments for missing parameters may do extra work may do extra work afterwardsafterwardspublic Car(int year, String make, String model, Color c) {public Car(int year, String make, String model, Color c) {
this(make, model, year, c);this(make, model, year, c);}}public Car(Color c) {public Car(Color c) {
this(“Generic”, “Auto”, 1997, new Color(127, 63, 70)); this(“Generic”, “Auto”, 1997, new Color(127, 63, 70)); // “rust”// “rust”}}
javadoc Commentsjavadoc Comments
Comments on classes and methodsComments on classes and methods used to build Web documentationused to build Web documentation between between /**/** and and */*/ description of class/methoddescription of class/method tags for class: @author, @version, …tags for class: @author, @version, … tags for method: @param, @return, …tags for method: @param, @return, …
javadoc Examplejavadoc Example
/** /** * A simple class.* A simple class. * @author Mark Young (A00000000)* @author Mark Young (A00000000)*/*/public class Simple {public class Simple { /** /** * A useless method.* A useless method. * @param n* @param n the count of somethingthe count of something * @param x* @param x the length of something elsethe length of something else * @return* @return a totally unrelated valuea totally unrelated value */*/ public String useless(int n, double x) {public String useless(int n, double x) { return “What?”;return “What?”; }}}}
Course RequirementsCourse Requirements
Class javadoc includes brief description and Class javadoc includes brief description and @author (with name and A-number)@author (with name and A-number)
Method/constructor javadoc requires brief Method/constructor javadoc requires brief description anddescription and @param for every parameter@param for every parameter @return for value-returning methods@return for value-returning methods @throws for checked exceptions thrown@throws for checked exceptions thrown
Pre- and Post-ConditionsPre- and Post-Conditions
Precondition: something that must be true in Precondition: something that must be true in order for the method to workorder for the method to work client’s responsibility to make sure it’s trueclient’s responsibility to make sure it’s true
» if it’s not true, then it’s the client’s fault the method if it’s not true, then it’s the client’s fault the method doesn’t workdoesn’t work
Postcondition: things that will be true after Postcondition: things that will be true after method is donemethod is done assumes preconditions are trueassumes preconditions are true
» otherwise “all bets are off”otherwise “all bets are off”
Static Fields and MethodsStatic Fields and Methods
““Static” = shared by all members of classStatic” = shared by all members of class common constantscommon constantspublic public staticstatic final double PI = 3.14159; final double PI = 3.14159; object countobject countprivate private staticstatic int numberOfCarsCreated = 0; int numberOfCarsCreated = 0;public public staticstatic int getNumberOfCarsCreated() int getNumberOfCarsCreated() special object creation methodsspecial object creation methodspublic public staticstatic Point cartesian(double x, double y) Point cartesian(double x, double y)public public staticstatic Point polar(double r, double theta) Point polar(double r, double theta) ……
Inheritance and PolymorphismInheritance and Polymorphism
Composition vs. InheritanceComposition vs. Inheritance InheritanceInheritance
adding fields and methodsadding fields and methods overridingoverriding polymorphismpolymorphism constructorsconstructors
InterfacesInterfaces
Composition vs. InheritanceComposition vs. Inheritance
Composition: “has a”Composition: “has a”» has that kind of an instance variablehas that kind of an instance variable
Person has a NamePerson has a Name Car has a ColorCar has a Color
Inheritance: “is a”Inheritance: “is a”» is that (more general) kind of a thingis that (more general) kind of a thing
Student is a PersonStudent is a Person Car is a VehicleCar is a Vehicle
InheritanceInheritance
Get all the public methods of another classGet all the public methods of another class the data, too, but it’s sort of hidden from youthe data, too, but it’s sort of hidden from you
Use “extends” in class declarationUse “extends” in class declarationpublic class Student public class Student extends Personextends Person
» a Student can do anything a Person can doa Student can do anything a Person can do» a Student has all the data a Person hasa Student has all the data a Person has
public class Car public class Car extends Vehicleextends Vehicle» a Car can do anything a Vehicle cana Car can do anything a Vehicle can» a Car has all the data a Vehicle hasa Car has all the data a Vehicle has
Inherited Methods and DataInherited Methods and Data
““Subclass” has all methods of “superclass”Subclass” has all methods of “superclass” Person has thinkAbout method…Person has thinkAbout method… ……so Student has thinkAbout methodso Student has thinkAbout method
» doesn’t need to even doesn’t need to even saysay it has the method it has the method includes getters and settersincludes getters and setters
» Person has getName method…Person has getName method…» ……so Student has getName methodso Student has getName method
Private data still private to the superclassPrivate data still private to the superclass Student must use getName/setNameStudent must use getName/setName
Adding Fields and MethodsAdding Fields and Methods
““Sub-class” can add new IVs and methodsSub-class” can add new IVs and methods just declare them like usualjust declare them like usualprivate double grade;private double grade;public double getGrade() { return grade; }public double getGrade() { return grade; } belong only to objects in the subclassbelong only to objects in the subclass
» Student has getGrade methodStudent has getGrade methoddouble studentsGrade = stu.getGrade();double studentsGrade = stu.getGrade();» Person doesn’t!Person doesn’t!double personsGrade = guy.double personsGrade = guy.getGrade()getGrade();;
• error: can’t find symbol method getGradeerror: can’t find symbol method getGrade
Overriding MethodsOverriding Methods
Subclass can add a method with same name Subclass can add a method with same name as one in the superclassas one in the superclass if different parameter list, then it’s an overloadif different parameter list, then it’s an overload if if samesame parameter list, then it’s an over parameter list, then it’s an overrideride
» it it replacesreplaces (hides/shadows) inherited method (hides/shadows) inherited method» subclass does same method in a different waysubclass does same method in a different way
add @Override before method definitionadd @Override before method definition
Object Class and MethodsObject Class and Methods
Every class inherits from ObjectEvery class inherits from Object directly or indirectlydirectly or indirectly
» if you don’t if you don’t saysay you extend, then you extend Object you extend, then you extend Object» if you do say, then if you do say, then itit extends Object (dir. or indir.) extends Object (dir. or indir.)
Some Object methods we often override:Some Object methods we often override:public String toString()public String toString()
» make a String that represents this objectmake a String that represents this objectpublic boolean equals(Object that)public boolean equals(Object that)
» check whether this object has same data as thatcheck whether this object has same data as that
PolymorphismPolymorphism
Subclass is a superclassSubclass is a superclass so when we need a superclass object…so when we need a superclass object… ……a subclass object will doa subclass object will do
» Need a Person? Use a Student!Need a Person? Use a Student!public static void public static void greet(Person p)greet(Person p) { … } { … }Person guy = new Person();Person guy = new Person();Student stu Student stu = new Student();= new Student();greet(guy);greet(guy); // guy is a Person// guy is a Persongreet(stu);greet(stu); // stu is a Person (all Students are)// stu is a Person (all Students are)
ConstructorsConstructors
Subclass object must be constructedSubclass object must be constructed but subclass object is a superclass object…but subclass object is a superclass object… ……so superclass object must be constructed, tooso superclass object must be constructed, too
» Java needs to be told how to do thatJava needs to be told how to do that use use super(…) super(…) to call superclass constructorto call superclass constructor
» give whatever information is relevantgive whatever information is relevantpublic Student(String name, double grade) {public Student(String name, double grade) { super(name);super(name); // calls Person(String name)// calls Person(String name) this.grade = grade;this.grade = grade;}}
Primary ConstructorsPrimary Constructors
Can’t use both Can’t use both this(…) this(…) and and super(…)super(…) both of them both of them needneed to be first to be first
» so you can only use one so you can only use one oror the other the other
Call Call super(…) super(…) from the primary constructorfrom the primary constructor for secondary constructors, use for secondary constructors, use this(…)this(…)
» call primary constructor, which then calls call primary constructor, which then calls super(…)super(…)
InterfacesInterfaces
Basically a list of method headersBasically a list of method headers operations something might be able to dooperations something might be able to do
Represent a “skill set”Represent a “skill set” says “what” but not “how”says “what” but not “how”
Sample interfacesSample interfaces List<T>: can keep track of a list of T objectsList<T>: can keep track of a list of T objects
» T is any reference type (class or interface)T is any reference type (class or interface) Comparable<T>: can be compared to T objectsComparable<T>: can be compared to T objects Comparator<T>: can compare T objectsComparator<T>: can compare T objects
Sample InterfaceSample Interface
Measurable: has an area and a perimeterMeasurable: has an area and a perimeterpublic interface Measurable public interface Measurable {{
/** get the area of this object/** get the area of this object * @return the area of this object */* @return the area of this object */ public double getArea();public double getArea();
/** get the perimeter of this object/** get the perimeter of this object * @return the perimeter of this object*/* @return the perimeter of this object*/ public double getPerimeter();public double getPerimeter();}}
Having the Skill SetHaving the Skill Set
Any class that has getArea and getPerimeter has the Any class that has getArea and getPerimeter has the skills necessary to be a Measurableskills necessary to be a Measurable but it must but it must telltell Java it has the skill set Java it has the skill setpublic class public class CircleCircle implements Measurable implements Measurable {{ private double radius;private double radius; public Circle(double r) { … }public Circle(double r) { … } public getRadius() { … }public getRadius() { … } public double getArea() { … }public double getArea() { … } public double getPerimeter() { … }public double getPerimeter() { … }}}public class public class Rectangle implements Measurable Rectangle implements Measurable {{ private double length, width;private double length, width; … …
PolymorphismPolymorphism
Interfaces can be used as data typesInterfaces can be used as data typespublic static double roundness(public static double roundness(Measurable mMeasurable m) {) { return 4 * Math.PI * return 4 * Math.PI * m.getArea() m.getArea() / Math.pow( / Math.pow(m.getPerimeter()m.getPerimeter(), 2);, 2);
}}
any class that implements the interface will doany class that implements the interface will do» but it has to say that it implements the interface….but it has to say that it implements the interface….
double rc = roundness(new Circle(10.0));double rc = roundness(new Circle(10.0));double rr1 = roundness(new Rectangle(10.0, 20.0));double rr1 = roundness(new Rectangle(10.0, 20.0));double rr2 = roundness(new Rectangle(0.4, 1000.0));double rr2 = roundness(new Rectangle(0.4, 1000.0));
1.0
rc0.698132
rr10.001256
rr2
GUI as an Example of I&PGUI as an Example of I&P
The JFrame classThe JFrame class components and layoutcomponents and layout inheriting from JFrameinheriting from JFrame
The ActionListener interfaceThe ActionListener interface adding an action listeneradding an action listener (anonymous action listeners?)(anonymous action listeners?)
The JFrame ClassThe JFrame Class
javax.swing.JFrame is a window classjavax.swing.JFrame is a window class constructor takes window titleconstructor takes window title need to set its size & make it visibleneed to set its size & make it visible
» otherwise it’s tiny and invisibleotherwise it’s tiny and invisibleJFrame win = new JFrame(“An Empty Window”);JFrame win = new JFrame(“An Empty Window”);win.setSize(300, 200);win.setSize(300, 200);win.setVisible(true);win.setVisible(true);
Window ComponentsWindow Components
Want to add stuff to the windowWant to add stuff to the windowwin.add(new JLabel(“Hello!”), BorderLayout.NORTH);win.add(new JLabel(“Hello!”), BorderLayout.NORTH);win.add(new JTextField(), BorderLayout.CENTER);win.add(new JTextField(), BorderLayout.CENTER);win.add(new JButton(“OK”), BorderLayout.SOUTH);win.add(new JButton(“OK”), BorderLayout.SOUTH);
» there are other ways to lay out the windowthere are other ways to lay out the window
New Window ClassesNew Window Classes
Create a class that extends JFrameCreate a class that extends JFrame class is another window classclass is another window classpublic class AdderDialog extends JFrame { … }public class AdderDialog extends JFrame { … }
Use constructor to add labels, buttons, Use constructor to add labels, buttons, etcetc..» we’re using a GridLayout (5 x 2) herewe’re using a GridLayout (5 x 2) here» and Unix…and Unix…
AdderDialog d;AdderDialog d;d = new AdderDialog();d = new AdderDialog();d.setVisible(true);d.setVisible(true);
Instance VariablesInstance Variables
Window needs to track its piecesWindow needs to track its pieces except for the labels – they do nothingexcept for the labels – they do nothingprivate JTextBox firstNumberBox;private JTextBox firstNumberBox;private JTextBox secondNumberBox;private JTextBox secondNumberBox;private JTextBox resultBox;private JTextBox resultBox;private JButton calculateButton;private JButton calculateButton;private JButton doneButton;private JButton doneButton;
Window Constructor TasksWindow Constructor Tasks
Constructor:Constructor: calls parent constructor: calls parent constructor: super(“Adding Numbers”);super(“Adding Numbers”); sets the sizesets the size sets layout: sets layout: this.setLayout(new GridLayout(5, 2));this.setLayout(new GridLayout(5, 2)); creates and adds the required elementscreates and adds the required elementsfirstNumberBox = makeNumberBox();firstNumberBox = makeNumberBox(); // private method// private method……this.add(new JLabel(“First number:”));this.add(new JLabel(“First number:”));this.add(firstNumberBox);this.add(firstNumberBox);……
Getting Some ActionGetting Some Action
Our buttons do nothingOur buttons do nothing» well, they change colour a bit when they’re clickedwell, they change colour a bit when they’re clicked
want them to do somethingwant them to do something need an object that knows how to react to themneed an object that knows how to react to them
» that object needs to listen for the button’s clickthat object needs to listen for the button’s click» that object needs access to the number boxesthat object needs access to the number boxes
the ActionListener interfacethe ActionListener interface» the actionPerformed(ActionEvent e) methodthe actionPerformed(ActionEvent e) method» the ActionEvent’s getSource() methodthe ActionEvent’s getSource() method
The ActionListener InterfaceThe ActionListener Interface
Knows how to respond to an eventKnows how to respond to an event create an ActionListener object (“AL”)create an ActionListener object (“AL”)public class AL implements ActionListener { public class AL implements ActionListener { public void actionPerformed(ActionEvent e) { … }public void actionPerformed(ActionEvent e) { … }}} tell button AL is listening to ittell button AL is listening to itdoneButton.addActionListener(new AL());doneButton.addActionListener(new AL()); click click AL’s actionPerformed method is called AL’s actionPerformed method is called
» but AL will need access to AdderDialog’s IVsbut AL will need access to AdderDialog’s IVs» maybe AdderDialog should maybe AdderDialog should bebe the ActionListener the ActionListener
Listening to Own ComponentsListening to Own Components
Have window implement ActionListenerHave window implement ActionListenerpublic class AdderDialog extends JFrame public class AdderDialog extends JFrame
implements ActionListener { … }implements ActionListener { … }» important: extends first, implements afterimportant: extends first, implements after
tell buttons that tell buttons that this window this window is listening to themis listening to themdoneButton.addActionListener(doneButton.addActionListener(thisthis););calculateButton.addActionListener(calculateButton.addActionListener(thisthis);); must now implement actionPerformedmust now implement actionPerformed
The actionPerformed MethodThe actionPerformed Method
Argument has information about the eventArgument has information about the event including its “source”: which button it wasincluding its “source”: which button it was
» choose action based on button clickedchoose action based on button clickedpublic void actionPerformed(ActionEvent e) {public void actionPerformed(ActionEvent e) { Object clicked = e.getSource();Object clicked = e.getSource(); if (clicked == doneButton) {if (clicked == doneButton) { System.exit(0);System.exit(0); // end program// end program } else if (clicked == calculateButton) {} else if (clicked == calculateButton) { addTheNumbers();addTheNumbers(); // private method// private method }}}}
Adding the NumbersAdding the Numbers
Private method to add and report resultPrivate method to add and report result use getText and Integer.parseInt to read #suse getText and Integer.parseInt to read #s use setText and Integer.toString to show resultuse setText and Integer.toString to show resultprivate void addTheNumbers() {private void addTheNumbers() { int n1 = Integer.parseInt(firstNumberBox.getText());int n1 = Integer.parseInt(firstNumberBox.getText()); int n2 = Integer.parseInt(secondNumberBox.getText());int n2 = Integer.parseInt(secondNumberBox.getText()); resultBox.setText(Integer.toString(n1 + n2));resultBox.setText(Integer.toString(n1 + n2));}}
ExceptionsExceptions
ExceptionsExceptions File Open ExceptionsFile Open Exceptions Input ExceptionsInput Exceptions The Exception ClassThe Exception Class The throws ClauseThe throws Clause
Adding the NumbersAdding the Numbers
Private method to add and report resultPrivate method to add and report result use getText and Integer.parseInt to read #suse getText and Integer.parseInt to read #s use setText and Integer.toString to show resultuse setText and Integer.toString to show resultprivate void addTheNumbers();private void addTheNumbers(); int n1 = Integer.parseInt(firstNumberBox.getText());int n1 = Integer.parseInt(firstNumberBox.getText()); int n2 = Integer.parseInt(secondNumberBox.getText());int n2 = Integer.parseInt(secondNumberBox.getText()); resultBox.setText(Integer.toString(n1 + n2));resultBox.setText(Integer.toString(n1 + n2));}}
ExceptionsExceptions
Objects that represent problems in programObjects that represent problems in program problems that the program itself might be able problems that the program itself might be able
to do something aboutto do something about
Throw and CatchThrow and Catch method with problem method with problem throwsthrows the exception the exception method that can deal with it will method that can deal with it will catchcatch it it method must be method must be readyready to catch it: to catch it:
» the try-catch controlthe try-catch control
The NumberFormatExceptionThe NumberFormatException
Exception in the AdderDialog programException in the AdderDialog program what if user enters text into number box?what if user enters text into number box?
» Integer.parseIntInteger.parseInt can’t change it to a number can’t change it to a number» throws a throws a NumberFormatExceptionNumberFormatException» AdderDialog does nothing about itAdderDialog does nothing about it
• addition FAILSaddition FAILS
can AdderDialog do anything about it?can AdderDialog do anything about it?» could set result box to “ERROR”could set result box to “ERROR”
• lets user know something’s wrong, at least!lets user know something’s wrong, at least!
Dealing with the ExceptionDealing with the Exception
Try to add the numbers; catch the exceptionTry to add the numbers; catch the exceptionprivate void addTheNumbers() {private void addTheNumbers() { try {try { int n1 = Integer.parseInt(firstNumberBox.getText());int n1 = Integer.parseInt(firstNumberBox.getText()); int n2 = Integer.parseInt(secondNumberBox.getText());int n2 = Integer.parseInt(secondNumberBox.getText()); resultBox.setText(Integer.toString(n1 + n2));resultBox.setText(Integer.toString(n1 + n2)); } catch (NumberFormatException nfe) {} catch (NumberFormatException nfe) { resultBox.setText(“ERROR”);resultBox.setText(“ERROR”); }}}}
» no exception: numbers get added upno exception: numbers get added up» exception: result gets set to “ERROR”exception: result gets set to “ERROR”
Try-Catch ControlTry-Catch Control
Try block contains the code we want to doTry block contains the code we want to do but might throw an exception we can deal withbut might throw an exception we can deal with
Catch block has code to deal with problemCatch block has code to deal with problem says what kind of problem it deals withsays what kind of problem it deals with
» e.g. e.g. NumberFormatExceptionNumberFormatException
If try block works, catch block gets skippedIf try block works, catch block gets skipped If exception happens, jump to catch blockIf exception happens, jump to catch block
remainder of try block gets skippedremainder of try block gets skipped
File I/OFile I/O
Exceptions also important for file i/oExceptions also important for file i/o problem trying to connect to the fileproblem trying to connect to the file
The The FileNotFoundExceptionFileNotFoundException trying to read from a file that doesn’t existtrying to read from a file that doesn’t exist trying to read from a read-protected filetrying to read from a read-protected file trying to create a file in a write-protected foldertrying to create a file in a write-protected folder
Need to deal with itNeed to deal with it it’s a “checked” exceptionit’s a “checked” exception
QuittingQuitting
Try to open a file with necessary dataTry to open a file with necessary dataScanner in = null;Scanner in = null;try {try { in = new Scanner(new File(“Important.dat”));in = new Scanner(new File(“Important.dat”));} catch (FileNotFoundException fnf) {} catch (FileNotFoundException fnf) { System.err.println(“Could not read important data.”);System.err.println(“Could not read important data.”); System.err.println(“Quitting.”);System.err.println(“Quitting.”); System.exit(1);System.exit(1);}}int importantNumber = in.nextInt();int importantNumber = in.nextInt();……
Trying AgainTrying Again
User chooses file to processUser chooses file to processScanner in = null;Scanner in = null;do {do { try {try { System.out.print(“Enter file name: ”);System.out.print(“Enter file name: ”); String name = kbd.nextLine();String name = kbd.nextLine(); in = new Scanner(new File(name));in = new Scanner(new File(name)); } catch (FileNotFoundException fnf) {} catch (FileNotFoundException fnf) { System.out.println(“Could not open that file.”);System.out.println(“Could not open that file.”); }}} while (in == null);} while (in == null);
Using System.outUsing System.out
Trying to create a file, but fail!Trying to create a file, but fail!PrintWriter out = null;PrintWriter out = null;try {try { System.out.print(“Enter file name: ”);System.out.print(“Enter file name: ”); String name = kbd.nextLine();String name = kbd.nextLine(); out = new PrintWriter(new File(name));out = new PrintWriter(new File(name));} catch (FileNotFoundException fnf) {} catch (FileNotFoundException fnf) { System.out.println(“Could not open that file.”);System.out.println(“Could not open that file.”); System.out.println(“Using System.out….”);System.out.println(“Using System.out….”); out = new PrintWriter(System.out);out = new PrintWriter(System.out);}}
Input ExceptionsInput Exceptions
Exceptions may happen in reading as wellExceptions may happen in reading as well user enters word where number expecteduser enters word where number expected
» InputMismatchExceptionInputMismatchException file runs out of data earlyfile runs out of data early
» NoSuchElementExceptionNoSuchElementException
Can deal with these as wellCan deal with these as well but don’t need tobut don’t need to
Input ExceptionsInput Exceptions
Read numbers from fileRead numbers from file» may be words in file; may be too few numbersmay be words in file; may be too few numbers
for (int i = 0; i < N; ++i) {for (int i = 0; i < N; ++i) { try {try { arr[i] = in.nextInt();arr[i] = in.nextInt(); } catch (InputMismatchException ime) {} catch (InputMismatchException ime) { arr[i] = -1;arr[i] = -1; // indicates bad input// indicates bad input in.next();in.next(); // skip bad input// skip bad input } catch (NoSuchElementException nse) {} catch (NoSuchElementException nse) { break;break; // no sense trying to read any more!// no sense trying to read any more! }}}}
Multiple Catch BlocksMultiple Catch Blocks
Can have as many catch blocks as you likeCan have as many catch blocks as you like each for a different kind of exceptioneach for a different kind of exception
Catch order Catch order maymay be important be important some exception classes inherit from otherssome exception classes inherit from others
» InputMismatchExcInputMismatchExcnn is a NoSuchElementExc is a NoSuchElementExcnn
» if you ask for an int, and the next thing is a word, if you ask for an int, and the next thing is a word, then there’s no such thing as what you asked forthen there’s no such thing as what you asked for
must put more specific exceptions firstmust put more specific exceptions first» IME must come before NSEEIME must come before NSEE
Never Catch ExceptionNever Catch Exception
Exception is most general exception classException is most general exception class if have if have catch(Exception e)catch(Exception e), it must come last, it must come last
But DON’T CATCH IT!But DON’T CATCH IT! it captures every kind of exceptionit captures every kind of exception
» including many you including many you shouldn’tshouldn’t deal with deal with what could you what could you possiblypossibly do that would deal do that would deal
with with every possible every possible kind of problem?kind of problem?
The throws ClauseThe throws Clause
If your code may throw a checked exception If your code may throw a checked exception and your method doesn’t deal with it, then and your method doesn’t deal with it, then you need to tell Java you you need to tell Java you won’twon’t deal with it deal with it
» that’s what being “checked” meansthat’s what being “checked” means add throws clause to method headeradd throws clause to method headerprivate static Scanner open(String name) private static Scanner open(String name)
throws FileNotFoundException throws FileNotFoundException {{
return new Scanner(new File(name));return new Scanner(new File(name));}}
QuestionsQuestions