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
Objects, Classes, Methods What is Object Oriented Programming? Object oriented Programming languages (OOP for short) include all the features of structured programming and add still more powerful ways to organize algorithms and data structures. There are three key features of OOP languages: encapsulation inheritance polymorphism All of them are tied to the notion of a class Java Programming page 1 769849215 Classes and Objects The primary distinguishing feature of OOP languages is the class. A class is a set of variables (data members) that can be associated with the methods which act on an object with the object itself. As the name object-oriented implies, objects are key to understanding objectoriented technology. You can look around you now and see many examples of realworld objects: your dog, your desk, your television set, your bicycle. These real-world objects share two characteristics: they all have state and they all have behavior. For example, cars have state (current gear, number of seats, four wheels, etc.) and behavior (braking, accelerating, slowing down, changing gears). Software objects are modeled after real-world objects in that they, too, have state and behavior. A software object maintains its state in variables and implements its behavior with methods. Java Programming page 2 769849215 Encapsulation As you can see from the above diagram, an object's variables make up the center or nucleus of the object. Methods surround and hide the object's nucleus from other objects in the program. This is called encapsulation. Typically, encapsulation is used to hide unimportant implementation details from other objects. Thus, the implementation details can change at any time without affecting other parts of the program. Java Programming page 3 769849215 The Benefits of Encapsulation Encapsulation provides two primary benefits to software developers: Modularity -- the source code for an object can be written and maintained independently of the source code for other objects. Also, an object can be easily passed around in the system. Information hiding -- an object has a public interface that other objects can use to communicate with it. But the object can maintain private information and methods that can be changed at any time without affecting the other objects that depend on it Java Programming page 4 769849215 What Are Classes? A class is a blueprint or prototype that defines the variables and methods common to all objects of a certain kind. Object3 Object2 Class Object1 In the real world, you often have many objects of the same kind. For example, your car is just one of many cars in the world. Using object-oriented terminology, we say that your car object is an instance of the class of objects known as cars. Cars have some state (current gear, number of seats, four wheels, etc.) and behavior (change gears, brake) in common. However, each car's state is independent of and can be different from other cars. Java Programming page 5 769849215 Defining a Class A class definition takes the following form: class MyClass { // the members of the class go here } The class keyword is followed by the class name, which must be a valid Java identifier. Example: class Employee { int empnum; // data member public int Num() { return empnum; } // method public void setNum(int newNum) { empnum = newNum; } // method } Java Programming page 6 769849215 In our example we will have many thousands of Employees. Each specific employee is an object. The definition of a Employee though, which we gave above, is a class. This is a very important distinction. A class defines what an object is, but it is not itself an object. An object is a specific instance of a class. Thus when we create a new object we say we are instantiating the object. Each class exists only once in a program, but there can be many thousands of objects that are instances of that class. To instantiate an object in Java we use the new operator. Here's how we'd create a new employee: Employee x = new Employee(); The members of an object are accessed using the . (dot) operator, as follows: Java Programming page 7 769849215 // Employee.java class Employee { int empnum; public int Num() { return empnum; } public void setNum(int newNum) { empnum = newNum; } } // data member // method // method class TestEmployee { public static void main(String[] args) { Employee emp1 = new Employee(); Employee emp2 = new Employee(); emp1.setNum(12651); emp2.setNum(36595); System.out.println("num of emp1 : " + emp1.Num()); System.out.println("num of emp2 : " + emp2.Num()); } } Java Programming page 8 769849215 Sample Run $ java TestEmployee num of emp1 : 12651 num of emp2 : 36595 Note when you compile the file Employee.java, you get two class files: Employee.class and TestEmployee.class. A member declared as public in a class is accessible to all other methods. A member declared as private in a class is accessible only to other members of the same class. A member which is not marked is said to be friendly and can directly accessible to other members of the same package. In particular, friendly accessible to all classes within the same java source file. Java Programming page 9 769849215 Overloading Methods Two methods can have the same name as long as they have different argument lists. This is called method overloading. Example // TestOverload.java class Employee { int empnum; public int Num() { return empnum; } public void Num(int newNum) { empnum = newNum; } } // data member // get method // set method class TestOverload { public static void main(String[] args) { Employee emp = new Employee(); emp.Num(98165); System.out.println("num of emp : " + emp.Num()); } } Java Programming page 10 769849215 Sample Run $ java TestOverload num of emp : 98165 Static Members (Class Members) Most properties, like the balance in bank account, are unique to the object. But some properties are shared among all objects of a given class. For example, the interest rate is a property shared by all saving accounts in the same bank. Such properties are called class member. Class members are defined using the keyword static. So class members are also called static members (e.g. Math class). Java Programming page 11 769849215 // TestStatic.java class Employee { static int MaxNum; int empnum; public int Num() { return empnum; } public void setNum(int newNum) { if (newNum<=MaxNum && newNum >1) empnum = newNum; } } // data member // data member // method // method class TestStatic { public static void main(String[] args) { Employee emp1 = new Employee(); Employee emp2 = new Employee(); emp1.MaxNum = 99999; System.out.println("MaxNum of emp2 : " + emp2.MaxNum); } } Java Programming page 12 769849215 Sample Run $ java TestStatic MaxNum of emp2 : 99999 Object3 Object2 Class (Static) Members Object1 (nonstatic members) MaxNum empnum Java Programming page 13 769849215 Static Methods Methods can also be declared static. A static method does not associate with any objects so that it cannot access nonstatic class members. Java allows programmer to call a static method using the name of the class rather than an object name. Example: The static method you are already very familiar with is public static void main(String[] args) Advantage of static methods: you don't have to create an object before using a static method. You can still call a static method using an object rather than a class name. Java Programming page 14 769849215 // TestStaticMethod.java class Employee { static int MaxNum; int empnum; // data member // data member public static void setMaxNum(int newMaxNum) { MaxNum = newMaxNum; } } class TestStaticMethod { public static void main(String[] args) { Employee.setMaxNum(88888); System.out.println("MaxNum of Employee : " + Employee.MaxNum); Employee emp = new Employee(); emp.setMaxNum(99999); System.out.println("MaxNum of emp : " + emp.MaxNum); } } Java Programming page 15 769849215 Sample Run $ java TestStaticMethod MaxNum of Employee : 88888 MaxNum of emp : 99999 Final Members It is possible to define a data member as final, meaning that its value is not changeable. A final variable must be initialised. (JDK1.1 introduced "blank final variable" which is simply a final variable that doesn't have an initializer. A blank final variable must be assigned an inital value, and that can be assigned only once.) Example: Java Programming class Employee { final static int MaxNum = 99999; //.... so on like before } page 16 // not modifiable 769849215 Object References Java has no explicit pointers. Instead, Java offers references. You might have noticed that a class object is not created the same way an intrinsic variable is created: int i; Employee emp = new Employee(); The declaration Employee an Employee object. emp // intrinsic variable // class object declares not an Employee object but a reference to Java will set any uninitialised reference to null. Any attempt to use a null reference generates an exception. You can assign any reference to refer to a real object: Employee emp; emp = new Employee(); Java Programming // emp references the null object // now emp references a real Employee object page 17 769849215 It is legal for two references to refer to the same object: Employee emp = new Employee(); Employee mgr = emp; // mgr refers to the same Employee as emp So What is a Reference? You can think of a reference as a name for an object. I have a dog. The dog is an object. I can name it Lucky. Lucky is a reference to the dog. I can give my dog several names: Lucky, Fido, Stupid. Each of these references refers to the same dog (object). A reference can be redirected. For example, I got another new dog and name it Lucky. When I say Lucky, I am referring to my new dog. This is similar to assigning a reference to point to a different object. Java Programming page 18 769849215 Passing References to Functions As all variables except intrinsic objects are references, a class object passed as an argument to a function remains modified in the calling function (call by reference). However, an intrinsic object does not remain modified when passed as an argument to a function (call by value). Java Programming Call by Value Call by Reference boolean byte short int long float double char all other objects page 19 769849215 // PassRef.java class Employee { int empnum; } // data member class PassRef { public static void main(String[] args) { Employee emp = new Employee(); emp.empnum = 81619; System.out.println("num of emp : " + emp.empnum); ModifyEmpNum(emp); // call by reference System.out.println("num of emp : " + emp.empnum); } private static void ModifyEmpNum(Employee Emp) { Emp.empnum = 71621; } } Sample Run $ java PassRef num of emp : 81619 num of emp : 71621 Java Programming page 20 769849215 Cleaning Up Lost Objects: Garbage Collection Object can get lost. Consider the following code segment: public static void SomeFunc() { //allocate an object Employee emp = new Employee(); // ... does something and then exits } Here the reference emp is local to the function SomeFunc. When the function exits, emp goes out of scope and the object is no longer accessible. Java is free to reclaim its memory and put it back into the heap. Java does the memory recovery in a process known as garage collection. Java performs garbage collection under the following circumstances: Whenever it needs to. When the amount of memory is not enough Whenever you ask. You can force garbage collection by calling System.gc. Whenever it gets around to it. Java continually runs a low priority background task that looks for things to throw away. Java Programming page 21 769849215 Constructor A constructor is a special method with the same name as the class that is invoked automatically whenever a class object is created. A constructor initialises all the variables and does any work necessary to prepare the class to be used. A constructor has no return type, not even void. If no constructor is defined by the programmer, a default "do-nothing" constructor is created for you. Java does not provide a default constructor if the class define a constructor of its own. Java Programming page 22 769849215 // TestConstructor.java class Employee { int empnum; public Employee() { empnum = 99999; } public Employee(int newNum) { empnum = newNum; } } // data member // constructor // constructor class TestConstructor { public static void main(String[] args) { Employee emp1 = new Employee(); System.out.println("num of emp1 : " + emp1.empnum); Employee emp2 = new Employee(81263); System.out.println("num of emp2 : " + emp2.empnum); } } Sample Run num of emp1 : 99999 num of emp2 : 81263 Java Programming page 23 769849215 What about Static Data? To initialise static data members, Java defines a special constructor for static members, called static initialiser. // TestStaticInit.java class Employee { static int MaxNum; static { MaxNum = 988; } } // static data member // static initialiser class TestStaticInit { public static void main(String[] args) { System.out.println("MaxNum of Employee : " + Employee.MaxNum); } } Sample Run $ java TestStaticInit MaxNum of Employee : 988 Java Programming page 24 769849215 Explicit Use of this pointer Sometimes it is necessary to use the this pointer explicitly within the member function. A typical example of this is to distinguish a local variable and data member which have the same name. You will find out more useof this pointer in the laboratory session. Java Programming page 25 769849215 toString All classes in Java are extending the class Object. One method in the Object class is toString which which will return a string that "textually represents" the object. public class Car { int seats; public static void main (String args[]) { Car c = new Car(); System.out.println("c = " + c.toString()); System.out.println("c = " + c); } } Sample Output c = Car@7672ed41 c = Car@7672ed41 You can override the toString method to produce more meaningful message. Java Programming page 26 769849215 class Car2 { int seats = 4; Sample Output c = Honda 4 c = Honda 4 public String toString() { return "Honda " + 4; } public static void main (String args[]) { Car c = new Car(); System.out.println("c = " + c.toString()); System.out.println("c = " + c); } } Additional Java features The break statement can also be labelled to allow control to pass out of multiple loops at one time by using break label. The statement break outHere does not pass control to the label. Rather, it passes control outside of the loop labelled outHere. Java Programming page 27 769849215 Example - Labelled Break // LabeledBreak.java Sample Output class LabeledBreak { i = 0, j = 0 i = 0, j = 1 i = 0, j = 2 i = 1, j = 0 i = 1, j = 1 i = 1, j = 2 i = 2, j = 0 i = 2, j = 1 Program exits. public static void main (String args[]) { int i = 0; outHere: while (i<4) { int j = 0; while (j<3) { System.out.println("i = "+i+", j = "+j); j++; if (i==2 && j==2) break outHere; } i++; } System.out.println("Program exits."); } } Java Programming page 28 769849215 Using the Standard I/O Objects Java provides three static standard objects for I/O: Object Type System.in BufferedInputStream System.out PrintStream System.err PrintStream Java views the input data as a sequential stream of bytes and System.in has a lower level method read() to read a number of bytes from the standard input. Reading String We can use the function System.out.write to print the byte array read. Let us begin by writing a very simple program that asks the user for their name and then prints a personalized greeting. Java Programming page 29 769849215 Remark : Don't run this example using FreeJava, use command line instead. // PersonalHello.java Sample Output import java.io.*; What is your name? John Hello John class PersonalHello { public static void main (String args[]) { byte name[] = new byte[100]; int nr_read = 0; System.out.println("What is your name?"); try { nr_read = System.in.read(name); System.out.print("Hello "); System.out.write(name,0,nr_read); } catch (IOException e) { System.out.print("I can't read your name."); } } } Java Programming page 30 769849215 The block try { ...... } catch (......) { ...... } is used to handle the exception generated by the run-time system. Some exceptions can ignored but the IOException must be caught. So the main method must have a try-catch block to handle any exception generated. Reading Numbers The object InputStream doesn't offer anything more sophisticated than read(bytes[]). So we have to convert the array of bytes to the type we need. This involves some works to convert the byte array to a String object and then parse it to the desired types. Java Programming page 31 769849215 // IOTest.java import java.io.*; public class IOTest { public static void main(String[] args) { int i; byte barray[] = new byte[80]; try { System.out.println("Enter an integer : "); System.in.read(barray); Sample Run $ java IOTest Enter an integer : 15231 15231 // convert the byte array to String String s = new String(barray); // remove all spaces from s // and convert the content to an integer i=Integer.parseInt(s.trim()); System.out.println(i); } catch (IOException ioe) { System.out.println(ioe.toString()); } } } Java Programming page 32 As parseInt() accepts a string containing digits only, trim() is used to remove all spaces. 769849215 Another method is to use DataInputStream which is used to read formatted data. // ReadNumber.java Sample Run import java.io.*; $ java ReadNumber Enter a number : 61347 i = 61347 class ReadNumber{ public static void main (String args[]) { String line; DataInputStream in = new DataInputStream(System.in); try { System.out.println("Enter a number : "); line = in.readLine(); int i = Integer.valueOf(line).intValue(); System.out.println("i = " + i); } catch (Exception e) { System.out.println(e); } } } Java Programming page 33 769849215 Reading Formatted Data If you enter any non-digit as the input to the above program, you will get a run-time syntax error. It is because the method Integer.valueOf accept signed numbers only. Sample Run $ java ReadNumber Enter a number : 7152__ java.lang.NumberFormatException: 7152 ended with two spaces $ java ReadNumber Enter a number : 71846. java.lang.NumberFormatException: 71846. To read text and numbers on the same line, you need to use the StreamTokenizer class. Java Programming page 34 769849215 Command Line Arguments You can pass command line arguments to your program. command line arguments java Hello May Tom Sue program name Compile the following program usual and run it with some command line arguments. // Hello.java class Hello{ Sample Output public static void main (String args[]) { System.out.print("Hello "); if (args.length == 0) System.out.println("whoever you are"); else { for (int i=0; i<args.length; i++) System.out.print(args[i]+" "); System.out.println(); } } >java Hello May Tom Sue Hello May Tom Sue >java Hello Hello whoever you are } Java Programming page 35 769849215