Download presentation
Presentation is loading. Please wait.
Published byErin Burke Modified over 9 years ago
1
Review of OOP in Java What you should already know…. (Appendices C, D, and E)
2
Outline Encapsulation Inheritance & Polymorphism GUI as an example of I & P Exceptions
3
Encapsulation Classes and objects: reference and co-reference data and operations Methods and constructors arguments and parameters overloading javadoc comments Static fields and methods
4
Classes and Objects Class encapsulates data and operations keeps them together in one place String name = “Mark Young”;// data int len = name.length();// 10 int space = name.indexOf(“ ”);// 4 (sic) String city = “Wolfville”;// more data String animal = city.substring(0,4);// “Wolf” Class: String objects: “Mark Young”, “Wolfville”, “Wolf” »object variables: name, city, animal
5
Classes, Objects and Variables Class is a kind of thing; a data type the kind of data and the available operations Object is an instance of the class; something a variable can refer to variables refer to, or point to, objects & name: “Mark Young” & city: “Wolfville” & animal: “Wolf” String variablesString objectsString operations get length find index of get substring …
6
Reference and Co-Reference Two variables can refer to the same object Car myCar = new Car(blue);// data Car disCar = myCar;// same object Car steves = new Car(blue);// same data disCar.setColor(green);// myCar is now green & myCar: & disCar: & stevesCar: Car variablesCar objectsCar operations … get colour change colour …
7
Data What we know about objects of this class class says what type it is object holds information Class Name: Car Data: make:(String) model:(String) year:(int) fuel (l):(double) mileage (km): (double) colour:(Color) Operations: … make:Toyota model:Corolla year:2009 fuel (l):23.7 mileage (km):164054.0 colour:RED myCar
8
Data Declaration Data saved in instance variables variables declared in the class access level (usually private, unless final) if final (never going to change) data type (int, double, String, Color, …) name public final String MAKE, MODEL; public final int YEAR; private double fuel, mileage; private Color colour;
9
Why Private? Why Public? IVs are made private to keep clients from messing them up accidentally or maliciously not allowed to say myCar.mileage = 10035.5; »error: mileage is PRIVATE! Final variables can’t get messed up given value when object created; never changes not allowed to say myCar.YEAR = 2013; »error: YEAR is FINAL!
10
Operations What we can do with objects of this class class says what’s available object carries out actions Class Name: Car Data: … Operations: get mileage drive some distance add fuel get colour change colour … make:Toyota model:Corolla year:2009 fuel (l):23.7 mileage (km):164054.0 colour:RED myCar make:Toyota model:Corolla year:2009 fuel (l):17.4 mileage (km):164150.3 colour:RED myCar myCar, drive 96.3 km.
11
Methods In OOP, operations become methods length operation length method change colour operation setColor method Methods addressed to objects usually thru a variable… name.length(), myCar.drive(96.3), … …but not necessarily! “Hello”.length(), Math.pow(10, 3), … “calling the method”
12
Method Header/Interface First line of method definition access level (operations public, helpers private) if static (shared by whole class) void or return type (int, double, String[], …) method name parameter list public void setColor (Color c) public Color getColor () public static double pow (double base, double exponent)
13
Parameters/Arguments Parameters are variables data type and name (double base, double exponent), (int n), (Color c), … Arguments are values of the correct type »int num = 10; (10.5, 3.14), (num), (new Color(0, 255, 0)), … Method call sets parameters to arguments base = 10.5; exponent = 3.14
14
Getters and Setters Methods to get some part of object’s data getter: getMileage, getFuel, getColor, … »most (non-final) IVs will have getters Methods to change some part of data setter: setColor »no setters for final instance variables »no setters for fuel and mileage but addFuel and drive will change them (“mutaters”)but addFuel and drive will change them (“mutaters”) “immutable” objects have no setters at all!
15
Referring to IVs Method definitions can refer to instance variables by name in any method mileage += distance; return colour; but to emphasize that it’s this object’s data: this.mileage += distance; return this.colour; »useful when a parameter has the same name: public void setColor(Color colour) { this.colour = colour;// IV colour set to parameter colour this.colour = colour;// IV colour set to parameter colour}
16
Private Methods Methods can be declared private client can’t use these methods »so not for the class operations they can only be called from inside this class »only to “help” this class carry out its operations public methods should check their parameters »to make sure they make sense private methods can assume they’re OK »if they’re not, then we need to fix our code
17
Overloading Methods in same class can share names called “overloading” the method (name) must have different parameter lists »different number of parameters »or different types of parameters related/similar operations public double addFuel(double x) { … } … »add given number of litres of fuel public double addFuel() { … } »fill the tank
18
Constructors Put the initial information into the object use “new” command give required data assign to a variable (usu.) Car myCar = new Car( “Toyota”, “Corolla”, 2009, Color.RED); »fuel and mileage start at 0.0 / myCar make:/ model:/ year:0 fuel (l):0.0 mileage (km):0.0 colour:/ myCar make:Toyota model:Corolla year:2009 fuel (l):0.0 mileage (km):0.0 colour:RED myCar
19
Constructor Definition Different from method definitions access usually public (but can be private, …) never static no void/return type at all name is same as name of class public class Car { public Car(String make, String model, int year, Color c) { …}
20
Constructor Purpose Make sure every instance variable gets a reasonable value what the client asks for it to be, if possible some reasonable default if client doesn’t say »may depend on what else client asks for Constructor is only place where a final variable can be given a value
21
Overloaded Constructors Like overloaded methods, must have different parameter lists public Car(String make, String model, int year, Color c) public Car(int year, String make, String model, Color c) public Car(String make, String model, int year) public Car(int year, String make, String model) public Car(Color c)
22
Primary Constructor Generally pick one constructor as primary it makes sure every IV gets a good value Other constructors call the primary: this(…) add in arguments for missing parameters may do extra work afterwards public Car(int year, String make, String model, Color c) { this(make, model, year, c); } public Car(Color c) { this(“Generic”, “Auto”, 1997, new Color(127, 63, 70)); // “rust” }
23
javadoc Comments Comments on classes and methods used to build Web documentation between /** and */ description of class/method tags for class: @author, @version, … tags for method: @param, @return, …
24
javadoc Example /** * A simple class. * A simple class. * @author Mark Young (A00000000) * @author Mark Young (A00000000)*/ public class Simple { /** /** * A useless method. * A useless method. * @param nthe count of something * @param nthe count of something * @param xthe length of something else * @param xthe length of something else * @returna totally unrelated value * @returna totally unrelated value */ */ public String useless(int n, double x) { public String useless(int n, double x) { return “What?”; return “What?”; }}
25
Course Requirements Class javadoc includes brief description and @author (with name and A-number) Method/constructor javadoc requires brief description and @param for every parameter @return for value-returning methods @throws for checked exceptions thrown
26
Pre- and Post-Conditions Precondition: something that must be true in order for the method to work client’s responsibility to make sure it’s true »if it’s not true, then it’s the client’s fault the method doesn’t work Postcondition: things that will be true after method is done assumes preconditions are true »otherwise “all bets are off”
27
Static Fields and Methods “Static” = shared by all members of class common constants public static final double PI = 3.14159; object count private static int numberOfCarsCreated = 0; public static int getNumberOfCarsCreated() special object creation methods public static Point cartesian(double x, double y) public static Point polar(double r, double theta) …
28
Inheritance and Polymorphism Composition vs. Inheritance Inheritance adding fields and methods overriding polymorphism constructors Interfaces
29
Composition vs. Inheritance Composition: “has a” »has that kind of an instance variable Person has a Name Car has a Color Inheritance: “is a” »is that (more general) kind of a thing Student is a Person Car is a Vehicle
30
Inheritance Get all the public methods of another class the data, too, but it’s sort of hidden from you Use “extends” in class declaration public class Student extends Person »a Student can do anything a Person can do »a Student has all the data a Person has public class Car extends Vehicle »a Car can do anything a Vehicle can »a Car has all the data a Vehicle has
31
Inherited Methods and Data “Subclass” has all methods of “superclass” Person has thinkAbout method… …so Student has thinkAbout method »doesn’t need to even say it has the method includes getters and setters »Person has getName method… »…so Student has getName method Private data still private to the superclass Student must use getName/setName
32
Adding Fields and Methods “Sub-class” can add new IVs and methods just declare them like usual private double grade; public double getGrade() { return grade; } belong only to objects in the subclass »Student has getGrade method double studentsGrade = stu.getGrade(); »Person doesn’t! double personsGrade = guy.getGrade(); error: can’t find symbol method getGradeerror: can’t find symbol method getGrade
33
Overriding Methods Subclass can add a method with same name as one in the superclass if different parameter list, then it’s an overload if same parameter list, then it’s an override »it replaces (hides/shadows) inherited method »subclass does same method in a different way add @Override before method definition
34
Object Class and Methods Every class inherits from Object directly or indirectly »if you don’t say you extend, then you extend Object »if you do say, then it extends Object (dir. or indir.) Some Object methods we often override: public String toString() »make a String that represents this object public boolean equals(Object that) »check whether this object has same data as that
35
Polymorphism Subclass is a superclass so when we need a superclass object… …a subclass object will do »Need a Person? Use a Student! public static void greet(Person p) { … } Person guy = new Person(); Student stu = new Student(); greet(guy);// guy is a Person greet(stu);// stu is a Person (all Students are)
36
Constructors Subclass object must be constructed but subclass object is a superclass object… …so superclass object must be constructed, too »Java needs to be told how to do that use super(…) to call superclass constructor »give whatever information is relevant public Student(String name, double grade) { super(name);// calls Person(String name) super(name);// calls Person(String name) this.grade = grade; this.grade = grade;}
37
Primary Constructors Can’t use both this(…) and super(…) both of them need to be first »so you can only use one or the other Call super(…) from the primary constructor for secondary constructors, use this(…) »call primary constructor, which then calls super(…)
38
Interfaces Basically a list of method headers operations something might be able to do Represent a “skill set” says “what” but not “how” Sample interfaces List : can keep track of a list of T objects »T is any reference type (class or interface) Comparable : can be compared to T objects Comparator : can compare T objects
39
Sample Interface Measurable: has an area and a perimeter 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();}
40
Having the Skill Set Any class that has getArea and getPerimeter has the skills necessary to be a Measurable but it must tell Java it has the skill set public class Circle 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 Rectangle implements Measurable { private double length, width; private double length, width; …
41
Polymorphism Interfaces can be used as data types public static double roundness(Measurable m) { return 4 * Math.PI * m.getArea() / Math.pow(m.getPerimeter(), 2); return 4 * Math.PI * m.getArea() / Math.pow(m.getPerimeter(), 2);} any class that implements the interface will do »but it has to say that it implements the interface…. double rc = roundness(new Circle(10.0)); double rr1 = roundness(new Rectangle(10.0, 20.0)); double rr2 = roundness(new Rectangle(0.4, 1000.0)); 1.0 rc 0.698132 rr1 0.001256 rr2
42
GUI as an Example of I&P The JFrame class components and layout inheriting from JFrame The ActionListener interface adding an action listener (anonymous action listeners?)
43
The JFrame Class javax.swing.JFrame is a window class constructor takes window title need to set its size & make it visible »otherwise it’s tiny and invisible JFrame win = new JFrame(“An Empty Window”); win.setSize(300, 200); win.setVisible(true);
44
Window Components Want to add stuff to the window win.add(new JLabel(“Hello!”), BorderLayout.NORTH); win.add(new JTextField(), BorderLayout.CENTER); win.add(new JButton(“OK”), BorderLayout.SOUTH); »there are other ways to lay out the window
45
New Window Classes Create a class that extends JFrame class is another window class public class AdderDialog extends JFrame { … } Use constructor to add labels, buttons, etc. »we’re using a GridLayout (5 x 2) here »and Unix… AdderDialog d; d = new AdderDialog(); d.setVisible(true);
46
Instance Variables Window needs to track its pieces except for the labels – they do nothing private JTextBox firstNumberBox; private JTextBox secondNumberBox; private JTextBox resultBox; private JButton calculateButton; private JButton doneButton;
47
Window Constructor Tasks Constructor: calls parent constructor: super(“Adding Numbers”); sets the size sets layout: this.setLayout(new GridLayout(5, 2)); creates and adds the required elements firstNumberBox = makeNumberBox();// private method … this.add(new JLabel(“First number:”)); this.add(firstNumberBox);…
48
Getting Some Action Our buttons do nothing »well, they change colour a bit when they’re clicked want them to do something need an object that knows how to react to them »that object needs to listen for the button’s click »that object needs access to the number boxes the ActionListener interface »the actionPerformed(ActionEvent e) method »the ActionEvent’s getSource() method
49
The ActionListener Interface Knows how to respond to an event create an ActionListener object (“AL”) public class AL implements ActionListener { public void actionPerformed(ActionEvent e) { … } public void actionPerformed(ActionEvent e) { … }} tell button AL is listening to it doneButton.addActionListener(new AL()); click AL’s actionPerformed method is called »but AL will need access to AdderDialog’s IVs »maybe AdderDialog should be the ActionListener
50
Listening to Own Components Have window implement ActionListener public class AdderDialog extends JFrame implements ActionListener { … } »important: extends first, implements after tell buttons that this window is listening to them doneButton.addActionListener(this); calculateButton.addActionListener(this); must now implement actionPerformed
51
The actionPerformed Method Argument has information about the event including its “source”: which button it was »choose action based on button clicked public void actionPerformed(ActionEvent e) { Object clicked = e.getSource(); Object clicked = e.getSource(); if (clicked == doneButton) { if (clicked == doneButton) { System.exit(0);// end program System.exit(0);// end program } else if (clicked == calculateButton) { } else if (clicked == calculateButton) { addTheNumbers();// private method addTheNumbers();// private method }}
52
Adding the Numbers Private method to add and report result use getText and Integer.parseInt to read #s use setText and Integer.toString to show result 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));}
53
Exceptions Exceptions File Open Exceptions Input Exceptions The Exception Class The throws Clause
54
Adding the Numbers Private method to add and report result use getText and Integer.parseInt to read #s use setText and Integer.toString to show result 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));}
55
Exceptions Objects that represent problems in program problems that the program itself might be able to do something about Throw and Catch method with problem throws the exception method that can deal with it will catch it method must be ready to catch it: »the try-catch control
56
The NumberFormatException Exception in the AdderDialog program what if user enters text into number box? »Integer.parseInt can’t change it to a number »throws a NumberFormatException »AdderDialog does nothing about it addition FAILSaddition FAILS can AdderDialog do anything about it? »could set result box to “ERROR” lets user know something’s wrong, at least!lets user know something’s wrong, at least!
57
Dealing with the Exception Try to add the numbers; catch the exception 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 up »exception: result gets set to “ERROR”
58
Try-Catch Control Try block contains the code we want to do but might throw an exception we can deal with Catch block has code to deal with problem says what kind of problem it deals with »e.g. NumberFormatException If try block works, catch block gets skipped If exception happens, jump to catch block remainder of try block gets skipped
59
File I/O Exceptions also important for file i/o problem trying to connect to the file The FileNotFoundException trying to read from a file that doesn’t exist trying to read from a read-protected file trying to create a file in a write-protected folder Need to deal with it it’s a “checked” exception
60
Quitting Try to open a file with necessary data Scanner in = null; try { in = new Scanner(new File(“Important.dat”)); in = new Scanner(new File(“Important.dat”)); } 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(); …
61
Trying Again User chooses file to process Scanner in = null; 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);
62
Using System.out Trying to create a file, but fail! PrintWriter out = null; 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) { 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);}
63
Input Exceptions Exceptions may happen in reading as well user enters word where number expected »InputMismatchException file runs out of data early »NoSuchElementException Can deal with these as well but don’t need to
64
Input Exceptions Read numbers from file »may be words in file; may be too few numbers 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;// indicates bad input arr[i] = -1;// indicates bad input in.next();// skip bad input in.next();// skip bad input } catch (NoSuchElementException nse) { } catch (NoSuchElementException nse) { break;// no sense trying to read any more! break;// no sense trying to read any more! }}
65
Multiple Catch Blocks Can have as many catch blocks as you like each for a different kind of exception Catch order may be important some exception classes inherit from others »InputMismatchExc n is a NoSuchElementExc n »if you ask for an int, and the next thing is a word, then there’s no such thing as what you asked for must put more specific exceptions first »IME must come before NSEE
66
Never Catch Exception Exception is most general exception class if have catch(Exception e), it must come last But DON’T CATCH IT! it captures every kind of exception »including many you shouldn’t deal with what could you possibly do that would deal with every possible kind of problem?
67
The throws Clause If your code may throw a checked exception and your method doesn’t deal with it, then you need to tell Java you won’t deal with it »that’s what being “checked” means add throws clause to method header private static Scanner open(String name) throws FileNotFoundException { return new Scanner(new File(name)); return new Scanner(new File(name));}
68
Questions
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.