Question? Leave a message!

Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions

Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions
Java Packages, Classes, Variables, Expressions, Flow Control, and ExceptionsSun’s Naming Conventions  Classes and Interfaces StringBuffer, Integer, MyDate  Identifiers for methods, fields, and variables name, getName, setName, isName, birthDate  Packages java.lang, java.util, proj1  Constants PI, MAXNUMBER www.ThesisScientist.comComments  Java supports three types of comments.  C style / multiliner comments /  C++ style // one liner comments  Javadoc / This is an example of a javadoc comment. These comments can be converted to part of the pages you see in the API. / www.ThesisScientist.comThe final modifier  Constants in Java are created using the final modifier. final int MAX = 9;  Final may also be applied to methods in which case it means the method can not be overridden in subclasses.  Final may also be applied to classes in which case it means the class can not be extended or subclassed as in the String class. www.ThesisScientist.comPackages  Only one package per file.  Packages serve as a namespace in Java and create a directory hierarchy when compiled.  Classes are placed in a package using the following syntax in the first line that is not a comment. package packagename; package packagename.subpackagename; www.ThesisScientist.comPackages (cont.)  Classes in a package are compiled using the –d option.  On the following slide, you will find the command to compile the code from the Proj1/src directory to the Proj1/bin directory. www.ThesisScientist.comPackages (cont.)  It is common practice to duplicate the package directory hierarchy in a directory named src and to compile to a directory named bin. Proj1 src The following command is run from the src directory: proj1 javac –d ../bin proj1/gui/ gui bin proj1 gui Example.class www.ThesisScientist.comPackages (cont.)  By default, all classes that do not contain a package declaration are in the unnamed package.  The fully qualified name of a class is the packageName.ClassName. java.lang.String  To alleviate the burden of using the fully qualified name of a class, people use an import statement found before the class declaration. import java.util.StringBuffer; import java.util.; www.ThesisScientist.comFields and Methods  In Java you have fields and methods. A field is like a data member in C++.  Method is like a member method in C++.  Every field and method has an access level. The public, private, and protected keywords have the same functionality as those in C++.  public  protected  private  (package) www.ThesisScientist.comAccess Control Same Modifier Subclass Same class Universe package private default protected public www.ThesisScientist.comAccess Control for Classes  Classes may have either public or package accessibility.  Only one public class per file.  Omitting the access modifier prior to class keyword gives the class package accessibility. www.ThesisScientist.comClasses  In Java, all classes at some point in their inheritance hierarchy are subclasses of java.lang.Object, therefore all objects have some inherited, default implementation before you begin to code them.  String toString()  boolean equals(Object o) www.ThesisScientist.comClasses (cont.)  Unlike C++ you must define the accessibility for every field and every method. In the following code, the x is public but the y gets the default accessibility of package since it doesn’t have a modifier. public int x; int y; www.ThesisScientist.comInstance and Local Variables  Unlike C++ you must define everything within a class.  Like C++,  variables declared outside of method are instance variables and store instance or object data. The lifetime of the variable is the lifetime of the instance.  variables declared within a method, including the parameter variables, are local variables. The lifetime of the variable is the lifetime of the method. www.ThesisScientist.comStatic Variables  A class may also contain static variables and methods.  Similar to C++…  Static variables store static or class data, meaning only one copy of the data is shared by all objects of the class.  Static methods do not have access to instance variables, but they do have access to static variables.  Instance methods also have access to static variables. www.ThesisScientist.comInstance vs. Static Methods  Static methods  have static as a modifier,  can access static data,  can be invoked by a host object or simply by using the class name as a qualifier.  Instance methods  can access static data,  can access instance data of the host object,  must be invoked by a host object,  contain a this reference that stores the address of host object. www.ThesisScientist.comPass By Value or By Reference  All arguments are passed by value to a method. However, since references are addresses, in reality, they are passed by reference, meaning…  Arguments that contain primitive data are passed by value. Changes to parameters in method do not effect arguments.  Arguments that contain reference data are passed by reference. Changes to parameter in method may effect arguments. www.ThesisScientist.comConstructors  Similar to C++, Java will provide a default (no argument) constructor if one is not defined in the class.  Java, however, will initialize all fields (object or instance data) to their zero values as in the array objects.  Like C++, once any constructor is defined, the default constructor is lost unless explicitly defined in the class. www.ThesisScientist.comConstructors (cont.)  Similar to C++, constructors in Java  have no return value,  have the same name as the class,  initialize the data,  and are typically overloaded.  Unlike C++, a Java constructor can call another constructor using a call to a this method as the first line of code in the constructor. www.ThesisScientist.comExpressions and Control Flow  Java uses the same operators as C++. Only differences are  + sign can be used for String concatenation,  logical and relative operators return a boolean.  Same control flow constructs as C++, but expression must return a boolean.  Conditional  if(boolean expression)…else if(boolean expression)…else…  switch(variable)case 1: …break; default:…  Variable must be an integral primitive type of size int or smaller, or a char www.ThesisScientist.comControl Flow Constructs (cont.)  Iterative  while (boolean expression) …  do … while (boolean expression);  for( initialize; boolean expression; update) …  break and continue work in the same way as in C++.  May use labels with break and continue as in C++. www.ThesisScientist.comControl Flow Constructs (cont.)  Enhanced for loop since Java 5 for iterating over arrays and collections. public class EnhancedLoop public static void main(String a ) Integer array = new Integer(5),6,7,8,9; for (int element: array) element is a local variable element+= 10; System.out.println(element); for (int element: array) System.out.println(element); www.ThesisScientist.comExample Class public class Person // instance data C++ style comments private String name; private int age = 21; private static int drivingAge = 16; private static int num = 0; //constructors public Person(String name) = name; static num tracks the num++; number of Person objects public Person(String name, int age) this(name); Call to previous constructor this.age = age; www.ThesisScientist.comExample Class (cont.) //accessor and mutators public String getName() return name; public void setName(int name) = name; The this reference is public int getAge() used to return age; differentiate between local and public void setAge(int age) instance this.age = age; data www.ThesisScientist.comExample Class (cont.) C style comments / static accessor methods The this reference does not exist in static methods / public static int getDrivingAge() return drivingAge; public static int getNum() return num; www.ThesisScientist.comExample Class (cont.) //overridden methods inherited from Object public String toString() return “Person “ + name; public boolean equals(Object o) if( o == null) return false; Testing if Object if( getClass() = o.getClass()) is a Person return false; Casting Object Person p = (Person)o; to a Person return this.age == p.age; End of class… no semicolon www.ThesisScientist.comExample Driver Program p Sally public class PersonTest 21 public static void main(String args) p2 Jane Person p = new Person(“Sally”); 21 Person p2 = new Person(“Jane”); Person p3 = new Person(“Mike”); p2 p3.setAge(25); M Miik ke e, p2); XX 21 compare(p2,p3); 25 public static void compare(Person p1, Person p2) p1 System.out.println(p1 + “ is “ + (p1.equals(p2) “”: “not”) + “ the same age as “ + p2); p2 www.ThesisScientist.comExceptions  Java handles exceptions like C++.  Place try block around problem code and a catch block immediately following try block to handle exceptions.  Different from C++…  Java uses a finally block for code that is to be executed whether or not an exception is thrown.  Java has a builtin inheritance hierarchy for its exception classes which determines whether an exception is a checked or an unchecked exception.  You may declare that a method throws an exception to handle it. The exception is then passed up the call stack.  Java forces the programmer to handle a checked exception at compile time. www.ThesisScientist.comException Hierarchy  Unchecked exceptions are derived from RuntimeException. Checked exceptions are derived from Exception. Error are also unchecked exceptions, but may not derive from it. Throwable checked Error Exception unchecked unchecked IOException RuntimeException checked www.ThesisScientist.comHandling the Exception Example public class HandleExample public static void main(String args) try String name = args0; System.out.println(args0); catch (IndexOutOfBoundsException e) System.out.println(“Please enter name ” + “after java HandleExample”); finally System.out.println(“Prints no matter what”); www.ThesisScientist.comPassing up the Exception  In Java you may pass the handling of the exception up the calling stack by declaring that the method throws the exception using the keyword throws.  This is necessary for compilation if you call a method that throws a checked exception such as the Thread.sleep method.  The Java API lists the exceptions that a method may throw. You may see the inheritance hierarchy of an exception in the API to determine if it is checked or unchecked. www.ThesisScientist.comPassing up the Exception Example public class PassUpExample public static void main(String args) System.out.println(“Hello”); main is obligated to handle try the exception since it is a checked exception passback(); catch(InterruptedException e) System.out.println(“Caught InterruptedException”); This method passes System.out.println(“Goodbye”); exception up call stack public static void passback() throws InterruptedException This method throws Thread.sleep(3000); a checked exception
Website URL
Document Information
User Name:
User Type:
United States
Uploaded Date: