Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
94.204* Object-Oriented Software Development Unit 4(b) Advanced Java Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 1 Advanced Java • There are a few areas in Java that are either completely new or that merit a good review due to their complexity or importance. – Strings – Class Methods and Variables – Visibility, Packages and Directory Structures – Exceptions Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 2 Java Strings • A string is a contiguous sequence of Unicode char – Like arrays, the compiler gives special support for strings to convert string literals ("This is a literal string") into String objects – There is no primitive type for a string • Recall, all primitive types fit into a computer word Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 3 Java Strings • Two classes support strings in Java – String class • Supports immutable string objects • This means that the string value cannot change in size or content once instantiated – StringBuffer class • Supports a string with content and size that can change (e.g. insert, append) • When do you use String vs. StringBuffer? – When one of the sets of methods is more appropriate for you than the other – When one behaviour is more efficient for you than the other Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 4 String Constructors • String () – Create a new String with value "" • String (String value) – Creates new String that is a copy of the String object value • The copy has a different reference • StringBuffer () and StringBuffer (String value) – Behave the same as String constructors String myString = new String (“Hello"); StringBuffer myString = new StringBuffer (“ World”); Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 5 String Methods • Many methods are defined for strings – length () returns the length of the string – charAt (int position) returns the Java char at the given position (from 0) – There are many more string methods • While entering your program, you can use JBuilder to browse the methods associated with a class – e.g. highlight the word StringBuffer in a source file. Right click over the highlighted name and select Browse Symbol at Cursor • The source code for the StringBuffer class will be brought up • Click on Doc in source browser window to see extensive documentation on the class • To return to editing your source files, click on the above the project browser window Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 6 Using String Variables • Print a concatenated string – a list of strings joined together System.out.println ( "My string is " + myString + “ and has length " + myString.length() + “ bytes"); Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 7 Using String Variables • Count the number of occurrences of each char String str = new String ("Here is a string"); int [] counts = new int [numOfUnicodeChars]; for (int i=0; i <str.length(); i++) { counts[str.charAt( i )]++; } Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 8 Comparing Strings • Two strings are equal if both have the same length and the same Unicode characters. • The == operator cannot be used for comparing strings. • You must use the equals method public boolean equals (Object anObject); – Performs a deep comparison of objects Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 9 Comparing Strings • Class Exercise : For each statement below, say whether it returns True or False. Explain. String s = new String ("Hello there"); String t = “Hello there"; String u = new String (t); a) s.equals( t )) b) s == t c) t == u Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 10 Class Methods and Variables • The variables and methods that we have looked at so far (with the exception of main() methods) are often referred to as instance variables and instance methods – each object (an instance of a class) has its own copy of the instance variables – instance methods (defined in the class) are invoked by sending messages to the object • e.g. anObject.msg ( data); Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 11 Class Methods and Class Variables • We can also define methods and variables with the static modifier • These are often called class methods and class variables • Class methods & variables are associated with the class itself, not with the instances of the class • Class methods & variables may be used before any instances of the class have been created (as well as after) . • Class methods & variables are usually accessed via the class’s name, not an object instance eg. ClassName.classMethod( arg ); eg. x = ClassName.classVariable Class methods can also be accessed via an instance eg. objectRef.classMethod( arg ); Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 12 Class Methods • Class methods can only access static members of the class – It belongs to the class, so it can’t “see” any of the instances (and their variables or methods) • Class methods are useful for : – Work independent of any instances – Helping in creating instances of the class – Calculations of the form y = f(x), where x has a primitive type • because x does not have class type (i.e., it is not an object) it does not have methods bound to it • Many examples in java’s Math class Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 13 Example: Using the Math Class • Example: add a method to class Complex that calculates the magnitude of a complex number public double magnitude() { return Math.sqrt( Math.pow(real, 2) + Math.pow(imag, 2)) } – sqrt(x) returns the square root of x – pow(x, y) returns x raised to the power y Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 14 Example: Using the Math Class • Notice the invocation of sqrt() in magnitude() • sqrt() is a static method in class java.lang.Math • Its argument is a double and it returns a double • sqrt() is invoked by sending the sqrt() message to its class; e.g., y = Math.sqrt(x); • Notice that we are not sending the sqrt() message to a Math object • pow() is also a static method in class Math Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 15 Class Variables • There is one copy of each class variable, regardless of the number of instances of the class that are created • Class variables are allocated usually at program startup or when the class is first used – before any objects of the class are created ! Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 16 Class Variables • Class variables are useful for : – Constants (final class variables) public static final double PI = 3.1415; – “Global data” or more specifically, data that is shared among all instances of the class eg. State variables, counters (next page) Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 17 Example: Counting Complex Objects • Add the following code to class Complex private static int count = 0; private static void incrementCount() { count++; } public static int numberCreated() { return count; } public Complex() { … Complex.incrementCount(); } Class exercise : What does it do ? Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 18 Example: Counting Complex Objects Recall : Class methods can be invoked by sending messages either to the class or to an object of the class. int nc; nc = Complex.numberCreated(); or : Complex c = new Complex(); nc = c.numberCreated(); But, an instance method can only be invoked by sending a message to an object: instanceName.methodname(); Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 19 Why is main() Static? • When we execute a Java program: java SomeClass – no instances of SomeClass exist, so the Java interpreter can't send a message to a SomeClass object – main() is static, so it can be invoked before any SomeClass objects have been created – therefore, the Java interpreter invokes SomeClass.main() Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 20 Static Initializers • A static initializer is a statement sequence that is executed when a class is first loaded • Used to initialize class variables and perform other initialization for the class class TV { // Array of channel numbers private static int [] channels = new int [nChan]; // Static initializer static { // For all channels allocate a channel number for (int i = 0; i < nChan; i++) { channels [i] = TunerClass.getChanNum(i); } } } © 2002, Systems and Computer Engineering, Copyright 21 Carleton University. 94.204-04b-JavaAdvanced.ppt Class Methods & Variables : Summary • Why does Java support class methods and variables? – sometimes, we think of a class as a factory that produces objects • class variables represent the state of the factory (not the state of the objects produced by the factory) • class methods implement the behaviours of the factory – to perform computation that involves values of primitive types (not objects) • e.g., java.lang.Math contains methods for performing floating point trigonometry, calculation of absolute values, exponentiation, etc. Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 22 Class Methods & Variables: Test Your Understanding • For 5 marks, explain why the following will not compile : public class WontWork { private int ns; // Instance variable public static void fns () { ns = 0; } } Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 23 Visibility, Packages and Directories • We’ve already seen that variables, methods and classes have access modifiers that limit their visibility to objects of other classes. public class Complex { private double real; private double imag; public Complex() {…} public Complex plus (Complex c) { return new Complex (real + c.real, imag + c.imag); } } Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 24 A Note About Instance Variable Visibility • Notice that plus() directly accesses the real and imag variables – of the Complex object that receives the message – of the Complex object referenced by parameter c • Students sometimes think that a method can access the private variables of the object that received the message, but cannot access the private variables of other instances of the same class • This is not true – A method defined in one class can access the private variables of any instance of the same class – A method defined in one class cannot access the private variables of objects that are instances of other classes Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 25 Visibility, Packages and Directories • Java has another mechanism for controlling the scope and visibility of variables, methods and classes : Packages. Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 26 Java Packages • A package represents a loose affiliation of classes (and interfaces - later..) • A package provides a name and scope for the group of classes • Many classes can be part of the same package • We could invent a package houseWares, containing classes such as: TV, Couch, Lamp and Fridge – These classes would typically all be stored in different files TV Couch Lamp Fridge package houseWares Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 27 Declaring Packages • Classes in a source file become part of a given package by using the package statement before any classes are declared In file TV.java // Claim membership in the houseWares package package houseWares; public class TV {…} In file Couch.java // Claim membership in the houseWares package package houseWares; public class Couch {…} • All classes in that source file become members of the specified package Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 28 Declaring Packages • If the package statement is not used, then all the classes in that file become members of Java's default anonymous package – All such classes are visible to each other • A class can be a member of only 1 package Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 29 Packages and Visibility • By default, a class is friendly (visible) to other classes in the same package (unless the class is nested in an enclosing class) • To gain visibility to the public classes stored with another package, you must import the class (or its entire package) • (An) import statement(s) must be declared after the package statement, and before any classes are declared Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 30 Packages and Visibility // Gain visibility to just the TV class import houseWares.TV; public class TvUser { TV myTv = new TV (); … } OR // Import all classes in houseWares import houseWares.*; public class HouseUser { Lamp myLamp = new Lamp( ); TV myTV = new TV( ); … } Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 31 Files and Packages • Each file can have only one public class (visible to classes in other files) – Can place several non-public classes in the same file with a public class • Java Packages provide a mechanism to: – Group functionally related classes for reuse by other programs • We can have more than one public class per package • Grouping several classes to form a package is is analogous to how data and methods are grouped to form a class – Make non-public classes, in different files, accessible to each other (and only to each other) by claiming membership in the same package Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 32 Files and Packages • Continued from previous slide …. – “Naming Disambiguation” • You can have two classes with the same name as long as they live in different packages. • Collision is avoided by importing the right package, or by calling the class with its long name. • Of course it is not desirable to use the same name for two classes, but it sometimes happens... Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 33 Packages and Directories • Each package is typically a separate directory that contains the files that are within that package • Nested packages can be created by layering directories and using hierarchical package names package myPkg.mySubPkg; would be stored in directory myPkg\mySubPkg and can be imported using // Import 1 class from the sub package import myPkg.mySubPkg.Myclass; // Import all classes from the sub package import myPkg.mySubPkg.*; Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 34 Standard Java Packages • Java supplies many packages – java.lang • Basic classes and interfaces used by most Java programs – java.util • Utility classes and interfaces such as date/time, randomizers, string manipulation – java.io • Classes that provide input/output for Java programs – java.text, java.applet, java.awt, java.net Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 35 The System Class in java.lang • About System.out.println(…) – System is a class in package java.lang that, by default, is imported by every Java file • out is an class variable (of type PrintStream defined in java.io) within the class System and is the Standard output stream • Similarly: – The System.err is a class variable of type PrintStream, can be used to report errors • Convenient because err is redirected to a file different than out – The System.in is a class variable of type InputStream also defined in java.io • in, out, and err are byte streams – A byte stream is a sequence of bytes Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 36 Study Exercise • Given the descriptions on the last slide, sketch out the code for the class System, including : – Package declarations and imports – Access modifiers – Instance Variables & methods • For full marks, use proper coding conventions – Indentation – Naming conventions • Hint : Attempt the code first and then check the code by browsing for the code in Jbuilder Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 37 What is an Exception ? • The compilation process will detect programming mistakes such as syntax errors and type mismatches. Such errors can therefore be referred to as compilation errors. • But once code is compiled and running, it will have to face the real world of erroneous input, inexistent files, hardware failure… Such problems are commonly known as runtime errors, which are likely to cause the program to abort. • It is therefore important to anticipate such problems and handle them correctly, by avoiding loss of data or premature termination, and by notifying the user. Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 38 Exceptions in this Course • Exceptions are an integral part of defensive programming – We want you to be in the habit, from the beginning, in using exceptions – We want to teach it now • But, exceptions are a complex topic, requiring an understanding of inheritance not yet taught. • At this point, we shall teach the basic exception mechanism. – You should be able to throw and catch any exceptions that we define for you. • Later, we shall examine the exception hierarchy, and teach you how to define your own exceptions. Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 39 Throwing Exceptions the throw statement • Suppose you have a class with a setLatitude() mutator (for example, the Geopoint class in the 94.202 notes): • You have to check whether the argument is within the degree range [-90 .. +90] • If this is not the case you can throw an IllegalArgumentException public void setLatitude(double l) { if ((l < -90) || (l > 90)) // is it within the range { throw new IllegalArgumentException(); } else { latitude = l; } } Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 40 Exception handling: catching • Now the calling method needs to do something with the exception that has been thrown by the invoked method, or the program will terminate abruptly! You need to catch the exception: • To catch an exception, you set up a try/catch block: public void setLatandLong(double lat, double long) { try { setLatitude(lat); setLongitude(long); } catch (IllegalArgumentException e) { System.out.println(“Wrong input!") } } Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 41 Exception handling: catching from Core Java Vol I: • “If any of the code inside the try block throws an exception of the class specified in the catch clause, then: – The program skips the remainder of the code in the try block. – The program executes the handler code inside the catch clause. • If none of the code inside the try block throws an exception, then the program skips the catch clause” Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-04b-JavaAdvanced.ppt 42