1 / 91

CISC121 – Lecture 5

CISC121 – Lecture 5. Last time: Method Overloading Arrays A few useful classes in Java: System Wrapper classes String class StringTokenizer ArrayList<T>. You Should Be:. Getting your assn 1 marks soon. Nearly finished Exercise 2. You Will Need To:. Finish Assn 2 by Thursday. Today.

reidar
Télécharger la présentation

CISC121 – Lecture 5

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CISC121 – Lecture 5 • Last time: • Method Overloading • Arrays • A few useful classes in Java: • System • Wrapper classes • String class • StringTokenizer • ArrayList<T> CISC121 - Prof. McLeod

  2. You Should Be: • Getting your assn 1 marks soon. • Nearly finished Exercise 2. CISC121 - Prof. McLeod

  3. You Will Need To: • Finish Assn 2 by Thursday. CISC121 - Prof. McLeod

  4. Today • Encapsulation • Javadoc • Testing and Debugging (some slides for reading?) CISC121 - Prof. McLeod

  5. Encapsulation • An OOP programming technique that: • Supports the re-usability of code. • Provides a well-defined user interface. • Builds into an Object the code that ensures the integrity of the data stored in the Object by: • Making sure that initial data values are “legal”. • Controlling (or preventing) changes to data. • Preventing “privacy leaks” when data is returned out of an Object. • Works well with modular design practices making code easier to write, test and debug. CISC121 - Prof. McLeod

  6. Encapsulation, Cont. • This is the driving principle for the design of all Objects in the Java API! • So, maybe you should design your own Objects using the same principle? Your class Java API CISC121 - Prof. McLeod

  7. An Example • Suppose you want to create a database to store records of Halloween visits. • For each year, you wish to record: • Number of munchkins banging at your door. • Outdoor temperature in deg C. • Weather condition – “rain”, “snow”, or “clear”. • You could create three arrays for each of the fields. • Difficult to code when moving records around… CISC121 - Prof. McLeod

  8. An Example, Cont. • It would be easier to create an Object that contains these three fields and then design a collection of these Objects. • No way the fields could get out of order since moving a record moves all fields at once. • The collection could be an array, an ArrayList or some other structure. • So, how to design an Object to hold this information? CISC121 - Prof. McLeod

  9. Halloween1 publicclass Halloween1 { publicint numMunchkins; publicint temperature; public String weatherCondition; } // end Halloween1 CISC121 - Prof. McLeod

  10. Halloween1, Cont. • In the main method in some other class: Halloween1[] hwDB = new Halloween1[100]; hwDB[0] = new Halloween1(); hwDB[0].numMunchkins = 200; hwDB[0].temperature = 10; hwDB[0].weatherCondition = "rain"; CISC121 - Prof. McLeod

  11. Halloween1, Cont. • Or with an ArrayList<T>: ArrayList<Halloween1> hwDBA = new ArrayList<Halloween1>(); Halloween1 hw = new Halloween1(); hw.numMunchkins = 200; hw.temperature = 10; hw.weatherCondition = "rain"; hwDBA.add(hw); CISC121 - Prof. McLeod

  12. Halloween1, Cont. • A question: Why not declare the attributes in Halloween1 static? CISC121 - Prof. McLeod

  13. Halloween1, Cont. • Another question: What is wrong with the following?: hwDB[1] = new Halloween1(); hwDB[1].numMunchkins = -200; hwDB[1].temperature = 100; hwDB[1].weatherCondition = "frogs"; CISC121 - Prof. McLeod

  14. Halloween1, Cont. • The object, hwDB[1] is not particularly realistic. • How can we prevent the creation of an object like this? • Who is responsible for checking for realistic, or “legal” values for the attributes? The Halloween1 class or the class that uses it? Where is it easiest to put these checks? CISC121 - Prof. McLeod

  15. Encapsulation, Cont. • Attributes must be declared private, so that the class that owns them can control how they are set. • If attributes are private then how can a user of the class assign the values of the attributes? • Through methods, of course! • Constructor(s) • Mutator(s) CISC121 - Prof. McLeod

  16. Encapsulation, Cont. • Within these methods, you can write code to check the parameters for validity. • What do you do if the values are not legal? Throw an exception! CISC121 - Prof. McLeod

  17. Defining Exceptions • You can throw an exception already defined in java, but: • Most of the time you will want to throw your own exception objects. • Why not? It’s easy! • See the next slide for the definition of an Exception object. (Please ignore indentation and line wrapping…) CISC121 - Prof. McLeod

  18. Defining Exceptions, Cont. public class IllegalHalloweenParametersException extends Exception { public IllegalHalloweenParametersException() { super("Illegal parameter value supplied to Halloween object."); } public IllegalHalloweenParametersException(String message) { super(message); } } // end IllegalHalloweenParametersException CISC121 - Prof. McLeod

  19. Defining Exceptions, Cont. • Inside a method that detects an illegal parameter: throw new IllegalHalloweenParametersException("Illegal number of kids."); • At the end of the method header that contains the above line of code: … throws IllegalHalloweenParametersException { CISC121 - Prof. McLeod

  20. Defining Exceptions, Cont. • This example contains a few Java keywords that we have not yet discussed: • extends • super • throw • throws • The exact meaning and usage of extends and super is beyond CISC121, but you can still write your own exceptions by following the provided pattern! CISC121 - Prof. McLeod

  21. Assigning Private Attributes - Constructor Methods • Constructors are special methods that have the same name as the class in which they reside, but have no return type (not even void). • They must be public. • They are only executed once, when the object is being instantiated. You can’t invoke them later. • Constructors are often overloaded. This means you can have many constructors with different parameter lists. Why do that? CISC121 - Prof. McLeod

  22. Halloween2 • Halloween2.java uses a constructor to set all parameters. • It also throws an exception if illegal values are encountered. • See how this object is used in TestHalloween2.java. • Note that this class is not complete – it only has the one constructor, for now. CISC121 - Prof. McLeod

  23. Assigning Private Attributes - Constructor Methods, Cont. • Note that once you have written a constructor with parameters, you can no longer use a constructor without any parameters, called the default constructor. • If you want an empty constructor, you must write one yourself, in addition to the parameterized constructor(s). • Why would you want an empty constructor? CISC121 - Prof. McLeod

  24. Assigning Private Attributes - Constructor Methods, Cont. • Suppose you don’t want to have to force the user to supply all parameters when he instantiates the object? How are you going to do this? • Suppose you want to edit parameters after you have created the object? How are you going to do this, too? Overload the constructors. Provide mutator(s). CISC121 - Prof. McLeod

  25. Assigning Private Attributes - Mutator Methods • Called “set” methods – in fact, by convention, the word “set” is the first word in the method name. • These methods must also check for legal parameters. • Usually the constructor invokes mutators, when they exist. • Should you write a mutator for each parameter? CISC121 - Prof. McLeod

  26. Halloween3 • Has overloaded constructors. • Has mutators. • A Halloween3 object can be created with or without the weather condition, but must have both the number of munchkins and the temperature. • All parameters can be changed later. • (Is still not yet complete…) CISC121 - Prof. McLeod

  27. Halloween3, Cont. • Note how the constructor invokes the mutators. • Mutators and constructors can throw the exception. • Note how the second, 2 parameter constructor uses the this keyword to invoke the three parameter constructor. • Note how the second constructor has to make an assumption for the value of weatherCondition (“unknown”). • Can you create an empty Halloween3 object? CISC121 - Prof. McLeod

  28. Aside, The this Thing • Can be used to supply a reference to the current object in that object’s code. • this means “myself”. • (When you invoke a method inside the same class, the compiler adds an implicit this keyword to each of those invocations.) CISC121 - Prof. McLeod

  29. Accessors • We have some useful ways to assign attributes, but how about getting them back out again? • Accessor methods return the value of an attribute. • By convention, accessor methods start with the word “get”. • One accessor per attribute. • For example: publicint getNumMunckins () { return numMunchkins; } // end getNumMunchkins Accessor CISC121 - Prof. McLeod

  30. Accessors, Cont. • These are pretty simple methods. • Except when you are returning an object. • Suppose we measured the temperature every hour and stored the values in an array of int[] called hourlyTemps. • What is wrong with the following? public int[] getHourlyTemps { return hourlyTemps; } // end getHourlyTemps Accessor CISC121 - Prof. McLeod

  31. Accessors, Privacy Leaks • Could the method receiving the pointer to the array hourlyTemps change the contents of the array? • How else can you do this? CISC121 - Prof. McLeod

  32. Accessors, Privacy Leaks, Cont. public int[] getHourlyTemps { int[] temp = new int[hourlyTemps.length]; for (int i = 0; i < hourlyTemps.length; i++) temp[i] = hourlyTemps[i]; return temp; } // end getHourlyTemps Accessor CISC121 - Prof. McLeod

  33. Accessors, Privacy Leaks, Cont. • Or: public int[] getHourlyTemps { return hourlyTemps.clone(); } // end getHourlyTemps Accessor • clone() is the only method that an array has. • It creates a deep (or non-aliased) copy of an array. • Either of these methods would prevent privacy leaks. CISC121 - Prof. McLeod

  34. Other Standard Methods • toString() • equals() • compareTo() • clone() • These are all properly coded in the, now complete, Halloween4 class. • It also contains Javadoc comments, which you can ignore for now. CISC121 - Prof. McLeod

  35. toString() Method • As it is, if we try to print a Halloween object, we will just get “gobbldeygook”: Halloween2@923e30 • (This String is composed of the object type and its hash code…) • So, to get a more useful view of the contents of the object, define a toString() method that returns a String. CISC121 - Prof. McLeod

  36. toString() Method, Cont. • This method will be called automatically whenever a String version of the object is needed. • (It overrides the toString() method from the parent Object class…) • You decide on how you want to represent your object as a String. • See the method in Halloween4, for example: CISC121 - Prof. McLeod

  37. In Halloween4: public String toString () { String s = numMunchkins + " kids, "; s += temperature + " deg C. and "; s += weatherCondition + "."; return s; } // end toString CISC121 - Prof. McLeod

  38. In TestHalloween4 • For example, the code: System.out.println(hwDB[0]); • Would print out: 200 kids, 10 deg C. and clear. • Note that you don’t need an explicit toString() call (but you can, if you want). CISC121 - Prof. McLeod

  39. equals() Method • Accepts another object of type Halloween4 and returns true of they are equal, false otherwise. • You get to define what “equality” means. • (Usually all the attributes have to match.) • Remember why you cannot use == to compare objects? CISC121 - Prof. McLeod

  40. equals() Method, Cont. • Two ways to write an equals() method (both will return true or false): • Accept a Halloween4 object as a parameter. • Accept an Object as a parameter (Object is the base class for all objects in Java!) • The proper way is the second one – then you will overwrite the equals() method inherited from the base, Object class (just take my word for this!). • (Outside the scope of CISC121, again…) CISC121 - Prof. McLeod

  41. equals() Method, Cont. publicboolean equals (Object otherObject) { if (otherObject instanceof Halloween4) { Halloween4 otherH = (Halloween4)otherObject; return numMunchkins == otherH.numMunchkins && temperature == otherH.temperature && weatherCondition.equalsIgnoreCase (otherH.weatherCondition); } // end if returnfalse; } // end equals CISC121 - Prof. McLeod

  42. equals() Method, Cont. • The instanceofkeyword checks to see if the supplied Object is indeed a Halloween4 object before it attempts to cast it. • Treat this code like the code you saw for the Exception class – follow the formula, and it will work! CISC121 - Prof. McLeod

  43. compareTo() Method • Compares a supplied Halloween4 object with the current one, based on your comparison criteria. • It returns an int value. • (Like the compareTo() method in the String class.) • You have to decide on the basis for comparison. • For Halloween4 you could just use numMunchkins, for example. CISC121 - Prof. McLeod

  44. compareTo() Method, Cont. • The base Object class does not have this method, so you don’t have to worry about writing one to take an Object as a parameter. CISC121 - Prof. McLeod

  45. clone() Method • Returns a deep copy of the current object. • Pretty easy for our Halloween4 object since it only stores primitive types and an immutable object. • See Halloween4.java for a complete version of the Halloween object! CISC121 - Prof. McLeod

  46. Javadoc • Javadoc.exe is a program that comes with the JDK. (It is in the same directory as javac.exe and java.exe). • If I have written a class, “MyClass.java”, that contains properly formatted comments (more below), then running “javadoc MyClass.java” generates a file “MyClass.html”. • The html file contains external documentation generated from the formatted comments in the source code. CISC121 - Prof. McLeod

  47. Javadoc - Cont. • Normal block comments in Java are delimited by “/*” and “*/”. Everything between these delimiters, usually multiple lines, is a comment. • Javadoc block comments are delimited by “/**” and “*/”. CISC121 - Prof. McLeod

  48. Javadoc - Cont. • The general form of a Javadoc comment: /** * Summary sentence. * More general information about the * class, attribute or method which * follows the comment, using as many lines * as necessary. (html tags can be included) * * javadoc tags to specify more specific * information, such as parameters and * return values for a method */ CISC121 - Prof. McLeod

  49. Javadoc - Cont. • The general form of a Javadoc tag is: @tagNamecomment • The tags you use depend on what you are describing (class, method or attribute). • In the case of methods, you can have a tag for each parameter, the return value, and a tag for each thrown exception. • Eclipse (really nice!!) will generate a blank tag for you after you type “/**”. • Typically, you will only write javadoc comments for public attributes and methods… CISC121 - Prof. McLeod

  50. Common Javadoc Tags CISC121 - Prof. McLeod

More Related