Selected Java Topics Introduction Basic Types, Objects and Pointers Modifiers Abstract Classes and Interfaces Exceptions and Runtime Exceptions Static Variables and Static Methods Type Safe Constants Swings and AWT Type Casting Java Development Environments Advanced Java Features 1-1 Introduction Java was introduced in May 1995 by Sun MicroSystems. A pure object oriented programming language. Highly portable - same byte code on all supported platforms. Secure and Internet ready. Just-in-time (JIT) compiler makes it comparable to native language (like C/C++). Based on C++ but removed many dangerous features. Build-in exception handling. 1-2
Basic Types, Objects and Pointers Basic types are NOT objects: boolean - true or false char (16-bit Unicode) byte (8-bit signed, from -128 to 127) short (16-bit signed, from -32,768 to 32,767) int (32-bit signed, from -2,147,483,648 to 2,147,483,647) long (64-bit signed, from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807) float (32-bit, range roughly ±3.40282347 1038, 6-7 significant decimal digits) double (64-bit, range roughly ±1.79769313486231570 10308, 15 significant decimal digits) Anything other than these basic types is an object. All objects are created in the system s memory heap. 1-3 Objects and Pointers Objects cannot be moved out from the memory heap. When we need to use an object, we create, in the local memory, a pointer to the desired object, and use that pointer instead. As a result, when programming Java, we are dealing with pointers most of the time. (Surprise!) 1-4
Pointer Arithmetic Pointer arithmetic allows programmers a very high degree of flexibility in programming. However, it will also cause serious problems if used carelessly. Unlike C and C++, Java does NOT allow pointer arithmetic. Therefore, Java is much safer than C and C++. 1-5 Parameter Passing In Java, all the parameters passed into a method are passed by value, that means a copy of the variables is made into the method s local memory. If the method changes the values of the parameters, the calling method will NOT be able to see the changes. 1-6
Parameter Passing If an object is passed into a method. It is actually the pointer to the object being passed in and copied. The result is that if the method changes the content of object, the calling method will be able to see the change. However, if the method assigns another object to the pointer passed in, the calling method will NOT be able to see the new object. 1-7 Example public class Test public static void toupper (String s) s = s.touppercase (); System.out.println (s); java Test hello HELLO hello public static void main (String [] args) String s = hello ; System.out.println (s); toupper (s); System.out.println (s); 1-8
Arrays Java also allows programmers to use arrays to hold collections of information. Arrays are real Java objects. The size of an array cannot be changed. The length member will tell us how many elements are in the array. int size = array.length; Java arrays are safer than C/C++ arrays as the Java Virtual Machine will check for boundary before allowing access to the elements stored in the array. 1-9 Garbage Collection All objects are created in the system s memory heap and are managed by the system s garbage collecting mechanism. If an object is no longer needed, the memory allocated to this object will be reclaimed on the next Garbage Collection. The users (or the programmers) do not have control on when the Garbage Collection will be executed. 1-10
Modifiers private friendly protected public final abstract static 1-11 private private class - only useful if defined as inner class (more on inner class later). private method - only the class that defines the method can use it. private variable - only the class that defines the variable can use it. 1-12
friendly The default modifier. friendly class - can be extended and instantiated by everyone in the same package. friendly method - can be used by everyone in the same package. friendly variable - can be used by everyone in the same package. 1-13 protected protected class - only useful if defined as inner class. protected method - can only be used by the class itself and its subclass, as well as everyone in the same package. protected variable - can only be used by the class itself and its subclass, as well as everyone in the same package. 1-14
public public class - can be extended and instantiated by everyone. There can be at most one public class in each Java file. The name of the file must be the same as the public class, with.java append as extension. public method - can be used by everyone. public variable - can be read and written by everyone. 1-15 final final class - a class that cannot be extended. final method - a method that cannot be overridden. final variable - a variable of which the value cannot be changed - i.e. it is a constant - a value must be provided when the variable is declared. final int PI = 3.15149; 1-16
abstract abstract class - a class that is declared with the abstract keyword. abstract method - a method that is declared with the abstract keyword, there is no need to provide implementation for abstract method. If a class contains any abstract method, it has to be declared as an abstract class. abstract and final cannot be used at the same time - i.e. a class or method cannot be abstract and final at the same time. 1-17 static static variable - a variable that belongs to the class, not to the object (instance of the class) - if one object changes its value, the change will be effective to all objects of the same class. static method - a method that belongs to the class, not to the object - it does not need an instance to be used. 1-18
Inner Class A class that is defined inside another class. Inner class is a member of its defining class, so it can use all other members (variable, method) from that class directly without passing in a reference of the object. 1-19 Abstract Classes and Interfaces An abstract class cannot be instantiated. An interface is a class that has only abstract methods. By default, all the methods in an interface should be public. 1-20
Abstract Classes A class that extends an abstract class will not be abstract if and only if it provides implementation to all the abstract methods that are defined in the super classes. Use an abstract class if you have some common implementation that would be beneficial to all the subclasses. 1-21 Interfaces Interfaces can be used to define the operations required to implement a class - we will use this technique extensively in our course. Interfaces are also useful if we have to extend from more than one class - Java does not support multiple inherence - i.e. it does not allow you to extend from more than one class - however, it allows your class to implement more that one interface. 1-22
Example Shape Circle Rectang le Triang le Line 1-23 Shape Interface public interface Shape public void draw (Location l, Color c); public void erase (); public void move (Location newlocation); 1-24
Shape Abstract Class public abstract class Shape private Location savedlocation; private Color savedcolor; private Color backgroundcolor; public void abstract draw (Location l, Color c); public void erase () draw (savedlocation, backgroundcolor); public void move (Location newlocation) erase (); draw (newlocation, savedcolor); 1-25 Exceptions and Runtime Exceptions Throwable Exception Error RuntimeException 1-26
Exceptions An exception condition will occur if: an exception is thrown inside the method the method calls another method that throws an exception. The exception must be handled by either: caught by a try-catch block; or declared in the method signature Java compiler will enforce that every Exception is handled properly. 1-27 Runtime Exceptions RuntimeException is extended from Exception. RuntimeException does not have to be declared in the method signature. RuntimeException can be handled as a regular Exception. However, if you are confident that the RuntimeException will not occur under certain situation, you do not have to catch them or declare them in the method signature. 1-28
Static Variables and Static Methods Static variables and static methods belongs to the class, not the object. Static variables and static methods can be used without creating the object first. Useful in implementing the Singleton pattern and in giving each object of the class an unique ID. 1-29 The Singleton Pattern A design pattern provides a ready-made solution to design problems. The singleton pattern is a design pattern in that we only want to have a single instance of the class. A singleton class usually does not allow the user to create the object directly. Instead it provides a method to get the instance. We enforce this by making the constructor of the class private or protected. 1-30
Singleton Example public final class Singleton static Singleton theonlyinstance = null; // declare the constructor private so the // user cannot create the instance directly private Singleton () public static Singleton getinstance () if (theonlyinstance == null) theonlyinstance = new Singleton (); return theonlyinstance; 1-31 Unique ID Example public class Student static private int nextid = 1; private int id; public Student () id = nextid++; public int getid () return id; public String tostring () return ( Student + id); 1-32
Java Constants Java allows us to define constants: public interface Season public static final int SPRING = 1; public static final int SUMMER = 2; public static final int FALL = 3; public static final int WINTER = 4; public static int gettemperature (int season); 1-33 Java Constants We can use the constants directly: int springtemperature = Season.getTemperature (Season.SPRING); What happens if we pass in a zero or negative number: int currenttemperature = Season.getTemperature (0); int currenttemperature = Season.getTemperature (-1); int currenttemperature = Season.getTemperature (5); All these code will compile correctly, but the code will give us problem during runtime. 1-34
Type Safe Constants Java also allows us to define type safe constants: public final class SeasonConstants public static final SeasonConstants SPRING = new SeasonConstants ( spring ); public static final SeasonConstants SUMMER = new SeasonConstants ( summer ); public static final SeasonConstants FALL = new SeasonConstants ( fall ); public static final SeasonConstants WINTER = new final SeasonConstants ( winter ); 1-35 Type Safe Constants private String name; private SeasonConstants (String name) this.name = name; public String tostring () return name; 1-36
Usage This is how you can use type safe constants: public interface Season public static int gettemperature (SeasonConstants season); int springtemperature = Season.getTemperature (SeasonConstants.SPRING); 1-37 Oops What happens if we pass in a zero or negative number: int currenttemperature = Season.getTemperature (0); int currenttemperature = Season.getTemperature (-1); int currenttemperature = Season.getTemperature (5); Oops, the compiler will not allow us to do this. 1-38
Discussion Why the constructor is defined as a private constructor? What happens if the constructor is not private? Why the class SeasonConstants is defined as a final class? What happens if the class is not a final class? Why the constants is defined as static constants? Will this give us any benefits? 1-39 Swing and AWT Swing is an extension of AWT (Abstract Window Toolkit) Swing has several advantages over AWT: Uniform look-and-feel across different platforms The look-and-feel is configurable More powerful components Fix some bugs on the AWT 1-40
Swing Swing was introduced in Java 1.1, but is not part of the Java core distribution until Java 1.2 In Java 1.1, swing components are distributed in the package com.sun.java.swing In Java 1.2 swing components are distributed in the package javax.swing 1-41 Swing and Applet Currently both Netscape 4.7 and Internet Explore 5.0 do NOT support Swing. Appletviewer that comes with JDK is the only browser that support Swing. If you are writing an applet and your target users are the open public, avoid using Swing. 1-42
Type Casting Type Casting is used to change an object of one type into another type. ClassCastException will be thrown if converting into an incompatible type. ClassCastException is a RuntimeException and needs to be caught if you are not sure whether the conversion will be successful or not. Two types of casting: upcasting downcasting 1-43 Upcasting Converting an object into one of its super classes. Example: Object obj = new MyClass (); Upcasting is implicit, i.e. you don t have to explicitly write anything to perform an upcasting (although you can.) Upcasting is safe and always possible. 1-44
Downcasting Converting an object into one of its subclasses. Example: MyClass myinstance = (MyClass) obj; Downcasting is not always safe. It is possible that an object will be downcast into an incompatible object (and as a result a ClassCastException will be thrown.) Therefore, downcasting is not implicit and needs to be written out (see example above) and ClassCastException needed to be caught if necessary. 1-45 Java Development Environments JDK (Java Development Kit) From Sun MicroSystems (http://www.sun.com) Current Release 1.4.1 Command line interface only free JCreator From Xinox Software (http://www.jcreator.com) Current Release 2.5 IDE Need JDK free Lite edition 1-46
IDEs DOs and DON Ts Editing Syntax Highlighting Parenthesis Matching Compilation Compile within IDE Errors Locating Debugging Break Points Stepping through Code Code Generation Produce proprietary (nonstandard Java) code Produce unnecessary code Visual Editing Hard to position components precisely Produce non-standard Java Code 1-47 Advanced Java Features Here is a list of some advanced Java features that we will not cover: Thread Programming (Using and programming) Java Beans RMI (Remote Method Invocation) JNI (Java Native Interface) Java2D and Java3D (Advanced Java Graphic Toolkits) For more information about these features, consult any good Java reference available from book stores. Some of these references are listed in the course web page and are available for download. 1-48