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
Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University Objectives • Upon completion of this course, you will be able to o o o o Understand the architecture of Java technology Use the various programming language features of Java Develop basic Java applications Write OO applications using Java Why Java? • Observations … o o o 4 million Java programmers and the community is growing at the rate of 30 percent a year Java is now running on everything from smart cards to the Mars Rover Java 2 Platform, Standard Edition v 1.4 hits the million mark In less than a month, the latest version of J2SE has been downloaded over a million times o o o o o More than 20,000 attendees in a recent Java developer conference (JavaOne) 100-million Java Consortium formed by some of the biggest software companies (IBM, Oracle, …) Number of Fortune 500 adopting Java More than 1/2 millions Java developers … (many many more!) Java’s Penetration ... History of Java • “Java’s ancestor was a toaster!” • Began life as a programming language for consumer electronics • C/C++ not up to task! (not chip-independent) History of Java (2) • 1990: James Gosling at Sun designing a language called “Oak”, a small, reliable, architecture-independent language • 1993: WWW appeared and took Internet “by storm” • Gosling and his team thought, “hey, this is bigger than we thought.” History of Java (3) • Sun wrote a new WWW browser named HotJava o First browser to support Java applets However, only “alpha” Java API • Netscape later announced Java support • Later a beta API, and soon a Java 1.0 API released • The rest is history What is Java? • From “The Java Language: A White Paper” (by Sun): “A simple, object-oriented, distributed, interpreted, robust, secure, architecture-neutral, portable, highperformance, multithreaded, and dynamic language” Simple • What’s simple? o o o o o Can learn quickly Looks familiar Poor programming features removed (e.g., no goto) No pointers Garbage collection - no memory leaks Object-Oriented • OO is ubiquitous! o • • • • • Lots of commercially produced code in C++ (and Java, Smalltalk, etc.) Focus on data, not procedures Encapsulates data and functions More “natural” Exploits inheritance (Almost) Everything in Java is an object! Distributed • Designed to support applications on networks Applets downloaded over the net o Resources accessed via URLs o • Socket class built in o easy to write clients and servers, collaborative programs • Reliable stream network connections • Furthers goal towards making the network is the computer Interpreted • Java compiler’s output is in “byte-code” format • Must run an interpreter to run these bytecodes Java Virtual Machine (JVM) is the interpreter o may be realized by software or hardware o JVM is built into AppletViewer, Netscape, IE, HotJava, etc. These bytecodes are architectureneutral o Architecture-Neutral • Bytecodes run on any machine, as long as an interpreter exists • Neutrality helps programmers -- no porting required o Unlike C/C++, no implementation-dependent features (e.g., int is always 4 bytes) • Using the AWT, we can create architecture-neutral windowing applications! o Abstract Windowing Toolkit (AWT) and “peer” classes give appropriate “look and feel” Architecture-Neutral (2) Java Source Java Compiler Java Bytecode JVM JVM JVM JVM Windows Solaris OS390 Mac “Write Once, Run Anywhere” Robust • Highly reliable • Helped by: o o o o o o Strong typing features Object-orientation Java Memory Model No Pointers Garbage Collection Exception Handling Secure • • • • Security is very important in networked environments No pointers Applet only: Can’t access any computers other than host Evolving security measures o o o JDK 1.02: sandbox (e.g., no disk I/O for applets) JDK 1.1: signed applets JDK 1.2 and beyond: “security policy” (with the SecurityManager class) • JVM enforces restrictions on applets • JAVA does not stand for “Just Allow Virtually Anything” Portable • Makes sure there are no implementationdependent aspects • Strong API • Java compiler: written in Java • Java run-time system: written in ANSI C High-Performance • Interpreted: won’t be as fast as C (getting closer every day though!) • Performance-critical applications: JIT (“just in time”) compilers • HotSpot technology (Sun), Jikes (IBM) • Native methods • The spectrum: o Tcl/Tk, shells < Java <= C and C++ Multithreaded • Multiple things at once • Supports multiple threads of execution (lightweight processes) o o garbage collection thread sound and animation • Java has built-in support for synchronization primitives o o Thread class built in synchronized keyword Dynamic • Dynamic class loading, as required, possibly over the net • Classes have run-time information • These classes can be anywhere on the Internet • All of this run-time loading is invisible to user How Do I Use Java (on the net)? • Web Users o transparent to you • Web Page Designers use the <APPLET> tag in HTML o thousands of applets out there! o • Java Developers o create Java applets, servlets (“server-side applets”), and/or JSP (Java Server Pages) Java Editions • Free download from http://java.sun.com o o o J2SE (Java 2 Standard Edition) J2EE (Java 2 Enterprise Edition) J2ME (Java 2 Micro Edition) J2SE J2SE Software Development Toolkit (SDK) • javac o o • java o • Java archive tool (JDK 1.1 only) javah o • allows applet to be run outside of a browser jar o • generates HTML documentation from Java source files (/** … */ segment) appletviewer o • Java virtual machine (i.e., the interpreter) javadoc o • Java compiler, converts .java to .class All Java source codes must be stored in files with .java extension Java C header and stub generator jdb o Java Debugger SDK (cont’d) • Java Package Library o o java.lang, java.io, java.awt, java.net, java.util, java.applet (JDK 1.02) java.beans, java.sql, java.rmi, … (a lot more) etc. (JDK 1.1, Java 1.2, Java 1.3) • JDK available in: o o o o o o Unix platforms Windows 95/98/NT/2000 OS/2 Macintosh Windows 3.1 OS 390 And more!!! Java IDE Tools • Eclipse (Apache Open Source Project) o • • • • • • • Based on IBM VisualAge for Java IBM WebSphere Application Developer (WSAD) BlueJ Borland JBuilder Oracle JDeveloper Symantec Visual Café Sun Forte for Java ... First Java Program: Hello, World! // This is a comment // The file is named HelloWorld.java public class HelloWorld { public static void main(String args[]) { System.out.println(“Hello World!”); } } • Note: If the class is public, the name of the class (i.e., HelloWorld) must be the same as the name of the file plus the .java extension (i.e., HelloWorld.java) main(): Not quite so simple anymore • In Java, we can’t simply write main() • We have to create main as a method in a Java class which returns nothing (void) • Furthermore, we must make this method public and static public: Anything can call it o static: It belongs to the class itself, not a instance of the class o println explained • What exactly is System.out.println(“...”)? System is a class It has a class variable named out out refers to an object of type PrintStream PrintStream objects have an instance method named println QED A Java Program Skeleton package MyPackage; // used if adding class to a package import packageName; // used if a package/class is to be “loaded” Bold - keywords accessType class ClassName extends SuperClass { // Field Declarations are given here accessType dataType fieldName; private int salary; // Method Definitions are given here accessType returnType methodName (parameter list) { … // method body } public void print () { System.out.println(“Salary is ” + salary); } } ClassName.java Access Types: private public protected default = “friendly” Applications and Applets • Applications are stand-alone o No security restrictions • Applets are designed for the web Security restrictions o Integrates with HTML o Shows up in WWW browser o In the last few years, two other kinds of Java programs have been introduced – Servlets and JSPs The “Hello World” Applet // HelloApplet.java import java.awt.*; import java.applet.*; public class HelloApplet extends Applet { Font f = new Font(“TimesRoman”, Font.BOLD, 36); public void paint(Graphics g) { g.setFont(f); g.setColor(Color.red); // draw string at x=5, y=50 (pixels) g.drawString(“Hello World!”, 5, 50); } } Java: The Programming Language Edit-Compile-Run Cycle in Java .java (source file) Compiler (e.g., javac ) .class (bytecodes) Java VM (e.g., java) output How to Compile and Run • Compile a source code file by typing javac <filename>.java (e.g., javac HelloWorld.java) o If no compile-time error appears, a .class file is produced. • Run an application by typing java <class name> (e.g., java HelloWorld) Not java HelloWorld.class Features Similar to C/C++’s • Same comment styles o new: /** to be processed by javadoc … */ • Same literals and data types new: true and false for the boolean data type o new: strings not null terminated, not mutable o new: numeric sizes and their machine independence o • Same operators • Same control structures Keywords short byte int else while do static package new import instanceof abstract throws throw volatile long float double boolean char class if for switch case break continue return final this super void public private protected default native transient const goto extends interface implements try catch finally synchronized Java’s Basic Constructs • Comments o o o // comment on one line /* comment on one or more lines */ /** documenting comments */ • Statements o o int x; // statement ends with a semicolon (;) x = 1 + 2; Primitive Data Types • There are 8 primitive data types in Java o All the numeric types (integer and floating point types) are signed (meaning they can be positive or negative). No unsigned numeric types in Java (unlike C/C++). • Three categories of data types: o o o Primitive data types Class data types (coming later) Interface data types (coming later) Basic Data Types • Integers o o o o byte (8 bits) short (16 bits) int (32 bits) long (64 bits) • Floats o o float (32 bits) double (64 bits) • Boolean o boolean (1 bit) • Characters o char (16 bits Unicode) • Strings o Primitive data types String (an example of class data type) capital case (because it is a class, not a primitive) Identifiers and Literals • Identifiers o o o case sensitive have no maximum length start with a letter, underscore, or dollar sign e.g., user_name, _file, $money • Literals o o o o numeric: 2 (int), 3L (long), 2.0f (float) 3.14 (double), 077 (octal), 0xDC (hex) character: ‘a’, ‘t’ boolean: true, false Watch out for these! string: “hello” Booleans • Has value true or false (different from numeric type) • Returned by relational operators • Required for conditional statements • E.g., o // if x is an int C/C++: if (x) { ...} // OK in C/C++, not OK in Java o Java: if (x == 1) { ...} o Strings • String is a “built-in” class provided by Java o e.g., String s1 = “Hi there!”; • The ‘+’ operator is used for String concatenation o o e.g., String s1 = “abc”; String s2 = s1 + “ ” + s1; • String objects represent constant strings (content cannot be altered) • Many methods supported in the String class Strings (2) • Examples String lastName = “Schaefer”; lastName.length() // gives 8 lastName.toUpper() // gives “SCHAEFER” lastName.toLower() // gives “schaefer” lastName.indexOf(“e”) // gives 4 lastName.indexOf(“x”) // gives –1 (for not found) lastName.indexOf(“e”,5) // gives 6 lastName.substring(2,5) // gives “hae” (1st index is inclusive, 2nd index is exclusive) Declarations & Assignments // TestDataType.java public class TestDataType { public static void main(String[] args) { int x = 1; float y = 3.1415f; Syntax (first look): objectRef.methodName(argument list) boolean truth = true; char c = ‘X’; String str1 = “Hello”, str2 = “World”, str3; str3 = str1 + str2; System.out.println("x="+x+"y="+y+"truth="+truth+"c="+c+"str3="+str3); System.out.println(“Length of str3 = “ + str3.length()); } } Note: If the + operation has a string involved, a concatenation of all the operands is performed. Java automatically converts all data involved to their string representations. Operators • Partial list (in order of precedence): o o o o o o o o o ++ (Preincrement, Postincrement) // increments a variable by 1 ++, -e.g., x = 1; System.out.println(x++); // displays 1 System.out.println(x); // displays 2 !, (type) e.g., x = 1; System.out.println(++x); // displays 2 System.out.println(x); // displays 2 *, /, % -- (Predecrement, Postdecrement) // decrements a variable by 1 e.g., x = 1; System.out.println(x--); // displays 1 +, System.out.println(x); // displays 0 e.g., x = 1; System.out.println(--x); // displays 0 System.out.println(x); // displays 0 <, >, <=, >=, instanceof ==, != (equal to and not equal to operators, respectively) && (this is the logical AND operator) || (this is the logical OR operator) =, *=, /=, +=, ... Casting and Promotion • Casting o o conversion of one data type to another data type Two ways to cast in Java: implicit - Java does it for you automatically For primitives, if expression on the right differs from the type of the variable on the left, automatic cast will happen if no possibility of losing information. The narrower data type will be promoted to the wider one. For objects, later on this. explicit - the programmer must take care of the casting For primitives, if expression on the right differs from the type of the variable on the left and there is a possibility of losing information. For objects, later on this. Promotion and Casting • e.g., // TestDataType2.java int x, y = 1; double z = 1.23; x = y / z; // compilation error x = y / (int) z; // OK x = (int) (y / z); // OK z = x; // OK Decision Structures • Syntax (if, else): if (boolean expr) { statements; } else { statements; } Note: else part is optional • Example: int status; ... if ( status == 1) { deduction = 500; marriedCount ++; } else { deduction = 100; singleCount ++; } Decision Structures (2) • Syntax (switch): switch (expr) { case expr1: stmt1; break; case expr2: stmt2; break; default: stmt; break; } • Example: switch (status) { case 1: marriedCount++; break; case 2: singleCount ++ break; default: // error; break; } Looping Structures • Syntax (for): for (initial expr; boolean expr; update expr) { statements; } • Example: for (int k = 0; k < 10; k++) { System.out.println(k); } Looping Structures (2) • Syntax (while): while (boolean expr) { statements; } • Examples: int k = 0; while (k < 10) { System.out.println(k); k++; } keepGoing = ‘y’; while (keepGoing == ‘y’) { … // determine if you need to keep going } Arrays • Arrays are objects • Like C/C++, subscripts start from 0 • No pointers in Java => no pointer arithmetic • To create an array, o use “new” e.g., int a[] = new int[5]; // creates an array of 5 ints same as: int [] a = new int[5]; o or array initializer int a[] = {1, 2, 3, 4, 5}; • To access an array element, use a[i] where 0 <= i < arraySize • Array boundaries are checked at runtime Arrays (cont’d) • The following will throw an exception (can be caught and handled) o e.g., int a[] = new int[5]; a[5] = 123; // array out of bound exception • Can use length to determine array size o e.g., public void doSomething ( int a[] ) { for (int i = 0; i < a.length; i++) a[i] = 0; } Passing an int array into a method Arrays (cont’d) • Creating an array of objects: o Student classList [] = new Student[25]; classList o classList[0] = new Student(); classList null null null … null aStudent null null … null … Arrays (cont’d) • Initial values: o o o // TestArray1.java String names [] = {“John”, “Mary”}; or String names [] = new String [2]; names[0] = “John”; names[1] = “Mary”; Can’t do this: int list[5]; // error: Can’t specify array dimension in type declaration int list2[]; // OK; declares list to be an array of int but does not allocate any space for it yet list2[0] = 1; // error: because list2 has not been not allocated any space. // Need to use: int list2[] = new int[10]; Arrays (cont’d) • Cannot resize arrays o o int myArray[] = new int[5]; // myArray is an array of 5 ints myArray = new int[10]; // myArray is a different array, with 10 ints // Will discuss this further in Objects • Copying arrays o o o o o Use System.arraycopy method int copyFrom[] = {10, 20}; int copyTo[] = {100, 200,300}; System.arraycopy(copyFrom,0, copyTo,0, copyFrom.length); Result: copyTo has {10,20,300}; Multi-Dimensional Arrays • Arrays of arrays int twoDim [][] = new int [4][]; twoDim [0] = new int [5]; twoDim [1] = new int [5]; twoDim [2] = new int [5]; twoDim [3] = new int [5]; o Alternatively, int twoDim [][] = new int [4][5]; Command Line Arguments • The entry point to your Java application must have the following method: o public static void main (String argv[]) {...} • argv[] must be present -- it holds the command line arguments • argv[0] gives the first argument • Use argv.length to get the number of arguments Command Line Arguments (2) • e.g., // TestCmdLine.java public class TestCmdLine { public static void main (String argv[]) { if (argv.length == 0) System.out.println(“No argument given!”); else for (int i=0; i < argv.length; i++) System.out.println(argv[i]); } } Naming Conventions • Methods & variables: o o Mixed case, starting with lower-case for the first word and each subsequent word starts with a capital letter E.g.,: myFirstMethod(), myBankAccount • Classes & interfaces: o o Mixed case, starting with upper-case for the first letter of the first word and each subsequent word starts with a capital letter E.g.,: MyClass, MyInterface Naming Conventions (cont’d) • Constants: o o Upper case, with words separated by underscores E.g.,: MY_LARGE_CONSTANT • Packages: o o All lower-case letters in all the words E.g.,: com.billylim.project1 Object-Oriented Programming with Java Classes • A class is a template (i.e., blueprint) for creating objects • A class extends another class (inheritance relationship) o e.g., public class className extends superclassName { ... } • By default, all classes are derived from a single root class called Object • All classes except Object have one immediate superclass Classes (2) // Student.java public class Student { private String name; // name is a field, attribute, or an instance variable public Student(String n) { // This is a constructor. Note that it has the name = n; // same name as the class name. More on this later. } public void setName (String n) { The getter and setter methods. Typically, get and set methods are defined for each field. name = n; If a field is named, say, workAddr, then a get } method named getWorkAddr() and a set method public String getName () { named setWorkAddr(…) are created. return name; } public void print () { System.out.println(“Name is “+name); } } Classes (3) // TestStudent.java (a dummy class to test the functionality of the Student class) public class TestStudent { public static void main (String argv[]) { Student s1 = new Student("Lee"); Student s2 = new Student("John"); s2.setName("John Jr."); s1.print(); System.out.println(s2.getName()); // can also use print() here } } • Note: The Student and TestStudent classes need to be in the same directory for the above to work properly. Objects • Objects/instances of classes are created using “new” o e.g., Student s = new Student(“John”); • A variable of non-primitive type actually holds “handle” for the actual object. It is called an object reference. • Assigning objects copies the handle, not the object. Objects (2) • Example: Student s1 = new Student(“Lee”); s1 Student s2 = s1; s1 Lee s2 s2.setName(“Lee JR.”); // whose name is changed? Aside: This is why System.arraycopy is needed to copy arrays Lee Objects (3) • Example: Student s1; // s1 has the value null s1 = new Student(“John”); s1 s1 = new Student(“Mary”); s1 John John John will be garbage collected Mary s1 = null; // what is the effect of this? Fields • Field creation o Syntax: optional accessType dataType fieldName; o Example: private int hoursWorked; private String name; • Field use o Syntax: fieldName (if inside the class) objectReference.fieldName (if outside the class and if the field is accessible) o Example: if (hoursWorked < 40) … // inside class employee1.hoursWorked = 37; // outside class Methods • Methods o o o o defined the behaviors of a class (called member functions in C++) can only be implemented in classes (no standalone code) must have a return type unless they are constructors (which have no return type) must have a comma separated list of pairs of parameter types and names (if takes no parameter, the list is empty) Method Definition • Syntax: optional [accessType] [modifier(s)] returnType methodName (parameter list) { … // method body } • Examples: public static void main(String[] args) { … } private int myMethod(int j, String s) { … } String myMethod2( ) { … } Constructors • Special methods that have the same names as their classes • Are invoked during the creation of an object by “new” • Constructors do not have a return type • Constructors (and methods in general) can be overloaded by varying the number of types of parameters Constructors (2) • Default constructor o A default constructor is automatically provided for you in every class Format: public MyClass() { // assume class name is MyClass } o Allows you to do: MyClass mc = new MyClass( ); o Will be invalidated if you add a constructor declaration with arguments Access Specifiers • As with C++, components of classes can have associated access specifiers o o o o public protected private “friendly” Accessible by all Only accessible from this class, its subclasses, and package. Only accessible from this class Accessible from the package; Default access (no specific declaration) Access Specifiers (2) • Accessibility Criteria Modifier public protected Default private Same Class Yes Yes Yes Yes Same Package Yes Yes Yes Subclass Yes Yes All Yes Access Specifiers (3) • Examine the classes Employee.java and TestAccess.java in your source disk. • Compile the class TestAccess.java and observe the output. (Should see an error message.) • Now change the name and salary fields to public and re-compile and run TestAccess.java. • Lesson: Keep instance variables/fields private! Argument/Parameter Passing • Java passes arguments by value only • When an object reference is passed as an argument to a method, a copy of the object reference is passed. o Thus, the contents of the actual object can be changed in the method, but the object reference itself is never changed. Argument/Parameter Passing • Example: … public static void main (String args[]) { int a = 10; String s = “hello”; Employee e = new Employee (“Mary”); method1(a, s, e); System.out.println(“a =“+a+”s=“+s+”e”+e); // prints 10, hello, and John } public static void method1 (int a2, String s2, Employee e2) { a2 = 100; s2 = “hello2”; e2.setName(“John”); e2 = new Employee(“Matt”); } Class Inheritance • We can “inherit” from other classes • Avoids coding things which have already been coded (i.e. reuse the structure and behavior already implemented) • Subclass inherits everything from the superclass, but programmer can add/change things in the subclass • Commonly referred to as the “is-a” relationship (also called Generalization/Specialization relationship) • We use the keyword extends to inherit in Java Inheritance (1) Fields: Superclass Methods: f1, f2, and f3 m1,m2, m3, m4, m5, and m6 Fields: Methods: f4 and f5 Subclass m6,m7, m8, and m9 An object of Superclass: An object of Subclass: Has 3 “slots” and understand messages m1-m6 Has 5 “slots” and understand messages m1-m5, m6 (as defined in the subclass) and m7-m9 All the fields and methods are inherited by the subclass A subclass may add additional fields (f4f5) and/or methods (m7-m9) and/or override an existing one (m6) Inheritance (2) // Person.java public class Person { private String name; public Person (String n) { name = n; } public void setName (String n) { name = n; } public String getName () { return name; } public void print () { System.out.println(“Name is “+name); } } // Student2.java public class Student2 extends Person { private float gpa; public Student2 (String n, float g) { super (n); // calls superclass constructor gpa = g; } public void setGpa (float g) { gpa = g; } public float getGpa () { return gpa; } public void print () { // overriding super.print(); // calls superclass print() System.out.println("gpa is” +gpa); } } Inheritance (3) // TestPersonStudent.java public class TestPersonStudent { public static void main (String argv[]) { Person p = new Person("Joe"); p.print(); Student2 s = new Student2("Joe", 0.0f); s.setName("Joe Jr."); // setName is inherited s.setGpa(4.00f); s.print(); } } Overriding vs. Overloading • Overriding o o o Subclass can specialize the methods of the superclass by changing the operation of a method declared by the superclass without changing the interface. Overridden method can be invoked using super Same method name, same parameter list, same return type, different body • Overloading o o A class can enhance its functionality by providing a means for the user to call a method with a different number of arguments or type. Same method name, same or different return type, different parameter list, different body Overloading: Example class Person { private String name; // overloaded constructor with no parameter public Person () { name = “ ”; } // overloaded constructor with 1 parameter public Person (String n) { name = n; } public void setName (String n) { … } public String getName () { … } public void print () { … } } public class TestPerson { public static void main (String argv[]) { Person p1 = new Person(); p1.print(); Person p2 = new Person(“John”); p2.print(); } } this and super Keywords • Sometimes it is necessary to refer to the instance of the object itself within a method or to refer to the superclass within a subclass. o o Use this to refer to the object itself Use super to refer to the super class this • Every instance method has a variable named this associated with it • this refers to the current object for which the method is being called • The this variable is used implicitly by the compiler when your method refers to an instance variable of the class this: Example public static void main (String args[]) { Student s1 = new Student (“John”); Course c1 = new Course(“Java”); c1.addAStudent(s1); // add student “John” to the course “Java” } public class Course { ... public void addAStudent (Student s) { add(this, s); // Let’s say this method can’t handle the add itself. // It needs to pass the necessary info to another method. } private void add (Course c, Student s) { // note that this is a private method … // real processing here } } this: Another Example public static void main (String args[]) { Person p = new Person (“John”); … } public class Person { private String name; … public Person (String name) { this.name = name; } … } field parameter this: Yet Another Example public class Student2 extends Person { … public Student2 () { this(“unknown”); // calling an overloaded constructor } public Student2 (String name) { this(name,0.0f); // calling an overloaded constructor } public Student2 (String name, float gpa) { super(name); this.gpa = gpa; } … } super: Example class Student extends Person { private float gpa; public Student (String n, float g) { super (n); gpa = g; } … } • Note: When using super and this in a constructor, it must be the first thing you do! i.e., super and this must be the 1st line. • Cannot use “super.super.varOrMethodName” to access a hidden variable or method two levels up in the inheritance hierarchy Abstract Classes • An abstract class allows the specifications of incomplete method definitions in a class (the methods are called abstract methods). The incomplete definitions are to be completed in the subclasses that inherit from the abstract class. • Benefits: o subclasses know the interface specified o subclasses are forced to implement the interface “A Parent gets to tell its children what to do!” • Note: Abstract classes cannot be instantiated. Abstract Classes: Example (1) Fields: 1. accountHolder 2. balance Account Methods: 1. Gets and sets for the fields 2. deposit 3. withdraw CheckingAccount SavingsAccount deposit() and withdraw() methods must be overridden by the CheckingAccount and SavingsAccount classes in order for them to be treated as a “concrete” class. If not, they become abstract as well. Can be made “incomplete,” i.e., give only the interface but not the implementation Abstract Classes: Example (2) abstract public class Transportation { private int speed; public class Car extends Transportation { public void transport (int speed) { // drive setGear(); pressPedal(); } public void print () { System.out.println("Speed =” +getSpeed()); System.out.println("Other Car related information"); } pubic void setGear() { … }; public void pressPedal() { … }; public abstract void transport (int speed); public abstract void print (); public void setSpeed (int s) { speed = s; } public int getSpeed () { return speed; } } } Note the semicolon (i.e., no method implementation here; just the interface) OO Characteristics: PIE • Polymorphism o Late binding mechanism • Inheritance o Through the use of extends • Encapsulation o o Class mechanism private access specifier Polymorphism • In Greek it means “many forms” • In OO/Java it means o o “one interface, multiple implementations” (e.g., a print interface with multiple implementations from the Person and Student classes) “One object reference, possibly referring multiple forms of objects” (e.g., Person x; Here x can be a Person, Student, etc.) Note: an object has only one form but an object reference can be of multiple forms (we say the object reference variable is polymorphic). Polymorphism: Example ... public static void main (String args[]) { HappyPerson list [] = new HappyPerson[3]; list[0] = new Student3(); list[1] = new Professor3(); list[2] = new HappyPerson(); for (int i = 0; i < list.length; i++) list[i].laugh(); } ... Output? public class HappyPerson { public void laugh() { System.out.println("Laugh Laugh Laugh"); } } public class Student3 extends HappyPerson { public void laugh() { System.out.println("HaHaHa"); } } public class Professor3 extends HappyPerson { public void laugh() { System.out.println("HeeHeeHee"); } } Miscellaneous The instanceof operator • When you are passed a polymorphic reference variable, sometimes you want to know what you actually have. Can find out using the instanceof operator. • Example: public void method1 (HappyPerson p) { if (p instanceof Student) { // Do something with a Student object // e.g., Student s = (Student) p; // The above fully restores the functionality of the object as a student // Without the cast, can’t perform: p.getGpa(); // OK to say: s.getGpa(); else if (p instanceof Professor) { // Do something with a Professor object else { // Do something with a regular happy person object } } Casting Objects • Use instanceof to test the type • Use casting to fully restore the functionality of an object • Rules: o Casts up hierarchy are done implicitly E.g., Person p = new Student(); o Downward casts must be done explicitly and are checked by the compiler E.g., Student s = (Student) p; // where p is of type Person o Object type is checked at runtime (runtime error may result) E.g., Student s = (Student) p; // where p is of type Person and it is // actually referring to a person object “has-a” Relationship • Oftentimes a relationship is of type “has-a” (also called association) instead of “is-a.” o E.g., A car has an engine, an employee has a department that he/she works for, etc. class Car { private Engine e; … } class Employee { private Department d; … } The == operator vs. equals() • The == operator performs equivalence test, i.e., x==y returns true if and only if x and y are referring to the same object. • The equals() method is overridden in classes in order to return true if the contents and type of two separate objects match o Note: if not overridden, the Object class will return false unless the two objects are the same. Example of == vs. equals() public class TestEqual { public static void main(String argv[]) { Student s1 = new Student("Billy"); Student s2 = new Student("Billy"); if (s1 == s2) System.out.println("s1 == s2"); if (s1.equals(s2)) // equals() should have been overridden to return true System.out.println("s1 equals s2"); String str1 = new String("abc"); String str2 = new String("abc"); if (str1 == str2) System.out.println("str1 == str2"); if (str1.equals(str2)) System.out.println("str1 equals str2"); String str3 = "abc"; String str4 = "abc"; if (str3 == str4) System.out.println("str3 == str4"); if (str3.equals(str4)) System.out.println("str3 equals str4"); } } Output str1 equals str2 str3 == str4 str3 equals str4 The final Keyword • Variables declared final must have a value assigned in their declarations. Attempt to change the variables will result in compilation error. o final int x = 10; • Methods declared final may not be overridden. o final void cannnotOverride(); • Classes declared final may not be subclassed. o final public class lastClass { … }; Static Variables • static Variables o o Only one copy of the variable is kept for all objects of the class (a class variable as opposed to an instance variable) e.g., public class Employee { static private String workAddress; } Static Methods • static Methods o o can only access static variable of the class implicitly final // TestStatic.java public class TestStatic { public static void main (String argv[]) { Professor p = new Professor(); p.setName("Billy"); p.setWorkAddress("ACS 5150, ISU"); p.print(); } } e.g., // Professor.java public class Professor { static private String workAddress; private String name; public void setWorkAddress (String addr){ workAddress = addr; } public static void setName (String n) { name = n; // compile-error! // Need to remove static is this case } public void print() { System.out.println("workAddress = " + workAddress); System.out.println("name = "+name); } } Static Methods (2) • Invoking static Methods e.g., // Professor2.java public class Professor2 { // TestStatic2.java public class TestStatic2 { static private String workAddress; public static void main (String argv[]) { private String name; Professor2 p = new Professor2(); public static void setWorkAddress (String addr){ p.setName("Billy"); workAddress = addr; p.setWorkAddress("ACS 9999, ISU, Normal, IL 61790"); } p.print(); public void setName (String n) { Professor2.setWorkAddress("ACS 1, ISU, Normal, IL 61790"); p.print(); name = n; } } } public void print() { System.out.println("workAddress = " + workAddress); System.out.println("name = "+name); } } Syntax (first look): class.methodName(argument list) Static Methods (3) • Another static method example: public class TestStatic3 { public static void main (String argv[]) { method1(); // Error: TestStatic3.java:3: Can't make static reference to method // void method1() in class TestStatic3. } public void method1 () { // Need to add “static” to remove the error above method2(); // Possible to call method2 if it is to remain a non-static method? } public void method2 () { System.out.println("method2 called!"); } } Concept of “Packages” • Obscene amount of Java classes on the net • Need a way to hierarchically classify them • Use an “inverse domain approach” o o e.g., edu.ilstu.acs.java.HelloWorld e.g., com.ibm.ivj.examples.TicTacToe • This allows us to place our classes on the Internet/Intranet/Extranet without fear of collision • Usually only need this for end result Packages (2) • package keyword enables grouping of classes • Package names are dot.separated (.) words and are stored in directories that match the words o e.g., java.Util.Date, java.Util.Dictionary, java.net.URL, ... • Package declaration must be specified at the beginning of the source file (only one permitted) package com.xyz.dept1; public class Employee { …} Packages (3) • Accessing packages using import o o class packages are loaded with the import keyword, specifying the package name as the path and the class name. Load multiple classes within a package with * (a class is not loaded until it is actually referenced in your code). o e.g., import java.util.Date; import java.awt.*; import com.xyz.dept1.*; Note: import java.awt.*; brings all classes in java.awt into the current namespace (does not load them). Also, it does not bring any (sub)packages! Need to use: import java.awt.event.*; if classes from java.awt.event are to made visible. Packages (4) • Classpath Environment Variable o In order for the compiler to locate a class, say, com.xyz.dept1.Employee, the classpath environment variable must be defined in the following way: set classpath=C:\com\xyz\dept1;. (Windows) setenv classpath=/com/xyz/dept1;. (Unix) Java Packages • Java language provides a suite of packages o o o o o o o o o o java.applet (applet functionality) java.awt (GUI components) java.io (I/O and file I/O stream classes) java.lang (language basics; automatically loaded) java.net (TCP/IP networking protocols) java.util (miscellaneous classes) java.beans (component model) java.sql (JDBC database support) java.rmi (remote method invocation, distributed computing) ... Exceptions • To help you build resilient code by allowing to catch error (i.e., exceptions) that are thrown and to handle the exception, when possible. • The Exception class defines mild error conditions that your program encounters and might want to handle o Examples: NullPointerException (attempt to access an undefined object or method), ArithmeticException (typically result of zero division), ArrayIndexOutOfBoundsException (array index out of bound) • The Error class defines serious error conditions (that your program should not try to recover from) o Examples: OutOfMemory Exception Classes • Class hierarchy: Object +--- Throwable +--- Error +--- VirtualMachineError +--- StackOverFlowError Don’t need to handle these +--- OutOfMemoryError +--- Exception +--- RunTimeException +--- ArithmeticException +--- NullPointerException +--- IndexOfBoundsException +--- ArrayIndexOfBoundsException +--- ... +--- IOException +--- FileNotFoundException ... +--- ... Exception Handling • Java provides exception handling facilities to find out what exception was thrown and try to recover • try and catch o o o use the try statement with code that might throw an exception that you are to handle use the catch statement to specify the exception to catch and the code to execute when caught e.g., try { // code that might throw an exception } catch (SomeExceptionType e) { // handle exception here } Exception Handling (2) • finally statement o o defines a block of code that is always executed, regardless of whether an exception is caught or not. E.g. [Yellin], try { startFaucet(); waterLawn(); } catch (BrokenPipeExceptionType e) { // handle exception here } finally { stopFaucet(); } Exception Handling: Example try { Output: int x = 0; Div by 0 int y; Clean Up, always! y = 1/x; Testing 456… System.out.println(“Testing 123…”); } catch (ArithmeticException e) { System.out.println(“Div by 0”); } finally { System.out.println(“Clean Up, always!”); } System.out.println (“Testing 456…”); More Exception Handling What if an exception is not caught? … main(String args[]) { try{ method1(…); Exception1 } caught catch (Exception1 e){ uncaught Exception1 propagated void method1(…) { method2(…); } // Code to handle exception1 } catch (Exception e){ // Code to handle a generic exception } finally{ // Code always to be executed } } uncaught Exception1 propagated void method2(…) { method3(…); // Exception1 thrown // from method3 } Appendix Interfaces • Interfaces are in the Java language mainly to provide much of the functionality of multiple inheritance, but without the difficulties. • Common usage: o Java guarantees that if you “implement(s)” an interface, you actually provide the necessary method(s). • A scenario: o Want Car and Boat to also have “Collectible” behavior Transportation Car Collectible Boat Interfaces (2) • Definition (of an interface): o a collection of method signatures (without implementations, always public and abstract) and/or constants (always public, static, and final) that can be added to a class to provide additional behaviors not defined in the class itself or inherited from its superclasses • Syntax: o o // To create an interface: public interface MyInterface [extends Interface1, Interface2, ...] { // all methods here are defaulted to public and abstract. // all variables here are defaulted to final, static, and public. } // To use an interface: public class MyClass implements MyInterface { // must implements all the methods specified in the interface MyInterface } Interfaces (3) public interface Comparable { public int compare(Sortable obj); } public class Student2 extends Person implements Comparable { private float gpa; … // all the methods from Student2 discussed earlier public int compare(Comparable obj) { Student2 s = (Student2) obj; return (gpa < s.gpa)? -1: 1; } } public class Sort { static void bubbleSort(Comparable [] sortArr) { for (int i = 0; i < sortArr.length; i++) for (int j = i; j < sortArr.length; j++) { Comparable temp = sortArr[i]; if ( temp.compare(sortArr[j]) > 0 ) { temp = sortArr[j]; sortArr[j] = sortArr[i]; sortArr[i] = temp; } // if } // for } // bubbleSort } // Sort Interfaces (4) public class TestInterface { public static void main(String args[]) { Student2 stuArr[] = new Student2[10]; for (int i = 0; i < stuArr.length; i++) { int rand = (int) (10 * Math.random()); String name = String.valueOf(rand); float gpa = (float) (4 * Math.random()); stuArr[i] = new Student2(name, gpa); } Sort.bubbleSort(stuArr); for (int j = 0; j < stuArr.length; j++) stuArr[j].print(); } } Interfaces (5) • Notes: o Interfaces are very commonly used in the AWT and the event model public class MyClass implements ActionListener { … public void actionPerformed(…) { …} } o Interfaces can extend multiple interfaces Wrapper Classes • Used for wrapping primitive data types so that they can be used as objects Primitive data types boolean byte char short int long float double Wrapper classes Boolean Byte Character Short Integer Long Float Double Wrapper Classes (cont’d) • Example: o int myInt = 1; Integer wrapperInt = new Integer (myInt); // do something with wrapperInt (e.g., insert it into a Vector) myInt = wrapperInt.intValue(); o int myInt2 = Integer.valueOf(“12345”).intValue(); o o o The Vector Class • Provides methods for working with dynamic arrays of varied elements o o Maintains a capacity and capacityIncrement. As elements are added, storage for the vector increases in chunks the size of the capacityIncrement Useful for dynamically storing heterogeneous collection of elements The Vector Class (2) import java.util.*; public class TestVector { public static void main(String args[]) { MyVector v = new MyVector() ; int digit = 5; float real = 3.14f; String s = new String ("Hi there!"); v.addInt(digit); v.addFloat(real); v.addString(s); v.printVector(); } } class MyVector extends Vector { public void addInt(int i) { addElement(new Integer(i)); // requires Object arg } public void addFloat(float f) { addElement(new Float(f)); } public void addString(String s) { addElement(s); } public void printVector() { Object o; int length = size(); System.out.println("Number of vector elements is " + length + " and are:"); for (int i = 0; i < length; i++) { o = elementAt(i); System.out.println(o.toString()); } } } References • Java Programming, Sun Microsystems, 1996-99. • Howell, Developing in Java, IBS, 1996. • Cornell & Horstmann, Core Java, 2nd Edition, Prentice-Hall, 1997. • van der Linden, P., Just Java and Beyond, 3rd Edition, PrenticeHall, 1998. • http://www.cs.ucla.edu/csd-grads-gs2/decuir/java/