class

Document Sample
class Powered By Docstoc
					                               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            71077c45-8f85-4308-8e13-250880d07df9.doc
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 object-
  oriented technology. You can look around you now and see many examples of real-
  world 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               71077c45-8f85-4308-8e13-250880d07df9.doc
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               71077c45-8f85-4308-8e13-250880d07df9.doc
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               71077c45-8f85-4308-8e13-250880d07df9.doc
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               71077c45-8f85-4308-8e13-250880d07df9.doc
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() {                       // method
                           return empnum;
                         }

                         public void setNum(int newNum) {         // method
                           empnum = newNum;
                         }
                     }




Java Programming                       page 6             71077c45-8f85-4308-8e13-250880d07df9.doc
 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                71077c45-8f85-4308-8e13-250880d07df9.doc
           // Employee.java

           class Employee {
             int empnum;                        // data member
             public int Num() {                 // method
               return empnum;
             }
             public void setNum(int newNum) {   // method
               empnum = newNum;
             }
           }

           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           71077c45-8f85-4308-8e13-250880d07df9.doc
           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               71077c45-8f85-4308-8e13-250880d07df9.doc
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;                              // data member
                     public int Num() {                       // get method
                       return empnum;
                     }
                     public void Num(int newNum) {            // set method
                       empnum = newNum;
                     }
                   }

                   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              71077c45-8f85-4308-8e13-250880d07df9.doc
                   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              71077c45-8f85-4308-8e13-250880d07df9.doc
              // TestStatic.java

              class Employee {
                static int MaxNum;                       // data member
                int empnum;                              // data member
                public int Num() {                       // method
                  return empnum;
                }
                public void setNum(int newNum) {         // method
                  if (newNum<=MaxNum && newNum >1)
                    empnum = newNum;
                }
              }

              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           71077c45-8f85-4308-8e13-250880d07df9.doc
               Sample Run
               $ java TestStatic
               MaxNum of emp2 : 99999




                                                  Object3


                                                       Object2
                   Class (Static)
                    Members
                     MaxNum
                                                             Object1
                                                            (nonstatic
                                                            members)
                                                             empnum




Java Programming                        page 13               71077c45-8f85-4308-8e13-250880d07df9.doc
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             71077c45-8f85-4308-8e13-250880d07df9.doc
              // TestStaticMethod.java

              class Employee {
                static int MaxNum;                            // data member
                int empnum;                                   // 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           71077c45-8f85-4308-8e13-250880d07df9.doc
              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:            class Employee {
                        final static int MaxNum = 99999;           // not modifiable
                        //.... so on like before
                      }


Java Programming                        page 16               71077c45-8f85-4308-8e13-250880d07df9.doc
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;                                     // intrinsic variable
       Employee emp = new Employee();             // class object

 The declaration Employee    emp   declares not an Employee object but a reference to
  an Employee object.

 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 references the null object
       emp = new Employee();    // now emp references a real Employee object




Java Programming                        page 17               71077c45-8f85-4308-8e13-250880d07df9.doc
 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                71077c45-8f85-4308-8e13-250880d07df9.doc
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).



                   Call by Value                 Call by Reference

                     boolean                     all other objects
                       byte
                      short
                        int
                       long
                      float
                      double
                       char




Java Programming                       page 19              71077c45-8f85-4308-8e13-250880d07df9.doc
                   // 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           71077c45-8f85-4308-8e13-250880d07df9.doc
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                71077c45-8f85-4308-8e13-250880d07df9.doc
 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               71077c45-8f85-4308-8e13-250880d07df9.doc
            // TestConstructor.java

            class Employee {
              int empnum;                              // data member
              public Employee() {                      // constructor
                empnum = 99999;
              }
              public Employee(int newNum) {            // constructor
                empnum = newNum;
              }
            }

            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              71077c45-8f85-4308-8e13-250880d07df9.doc
   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 data member
                static {                     // static initialiser
                  MaxNum = 988;
                }
              }

              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              71077c45-8f85-4308-8e13-250880d07df9.doc
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               71077c45-8f85-4308-8e13-250880d07df9.doc
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 {                                                 Sample Output
       int seats;
          public static void main (String args[]) {                     c = Car@7672ed41
           Car c = new Car();                                           c = Car@7672ed41
           System.out.println("c = " + c.toString());
           System.out.println("c = " + c);
        }
    }


 You can override the toString method to produce more meaningful message.




Java Programming                         page 26              71077c45-8f85-4308-8e13-250880d07df9.doc
     class Car2 {
        int seats = 4;                                                     Sample Output
                                                                            c = Honda 4
           public String toString() {                                       c = Honda 4
               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             71077c45-8f85-4308-8e13-250880d07df9.doc
Example - Labelled Break
// LabeledBreak.java                                                     Sample Output
class LabeledBreak {                                                     i = 0, j = 0
                                                                         i = 0, j = 1
    public static void main (String args[]) {                            i = 0, j = 2
      int i = 0;                                                         i = 1, j = 0
      outHere:                                                           i = 1, j = 1
      while (i<4) {                                                      i = 1, j = 2
        int j = 0;                                                       i = 2, j = 0
        while (j<3) {                                                    i = 2, j = 1
                   System.out.println("i = "+i+", j = "+j);              Program exits.
                   j++;
                   if (i==2 && j==2)
                     break outHere;
            }
            i++;
        }
         System.out.println("Program exits.");
    }
}




Java Programming                        page 28         71077c45-8f85-4308-8e13-250880d07df9.doc
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             71077c45-8f85-4308-8e13-250880d07df9.doc
   Remark : Don't run this example using FreeJava, use command line instead.

       // PersonalHello.java                                           Sample Output
       import java.io.*;                                               What is your name?
                                                                       John
       class PersonalHello {                                           Hello John
         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           71077c45-8f85-4308-8e13-250880d07df9.doc
 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               71077c45-8f85-4308-8e13-250880d07df9.doc
 // IOTest.java                                                   Sample Run
 import java.io.*;
 public class IOTest {                                            $ java IOTest
   public static void main(String[] args) {                       Enter an integer :
     int i;                                                       15231
     byte barray[] = new byte[80];                                15231
     try {
       System.out.println("Enter an integer : ");
       System.in.read(barray);

              // 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());                       As parseInt() accepts a
         }                                                           string containing digits
     }                                                               only, trim() is used to
 }                                                                   remove all spaces.


Java Programming                       page 32           71077c45-8f85-4308-8e13-250880d07df9.doc
     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 :
class ReadNumber{                                                          61347
  public static void main (String args[]) {                                i = 61347
    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              71077c45-8f85-4308-8e13-250880d07df9.doc
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
                                                                           ended with two
                   $ java ReadNumber                                       spaces
                   Enter a number :
                   7152__
                   java.lang.NumberFormatException: 7152

                   $ 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             71077c45-8f85-4308-8e13-250880d07df9.doc
Command Line Arguments

 You can pass command line arguments to your program.
         java Hello May Tom Sue               command line arguments

                     program name
 Compile the following program usual and run it with some command line
  arguments.
     // Hello.java                                         Sample Output
     class Hello{
                                                           >java Hello May Tom Sue
         public static void main (String args[]) {         Hello May Tom Sue
           System.out.print("Hello ");
           if (args.length == 0)                           >java Hello
             System.out.println("whoever you are");        Hello whoever you are
           else {
             for (int i=0; i<args.length; i++)
               System.out.print(args[i]+" ");
             System.out.println();
           }
         }
     }


Java Programming                    page 35                71077c45-8f85-4308-8e13-250880d07df9.doc

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:17
posted:11/20/2011
language:English
pages:35