Anda di halaman 1dari 151

SPECIAL JAVA SUBJECT

OBJECT ORIENTED PROGRAMMING


CLASSES AND OBJECT

Outline

Working with Classes and Objects Defining Classes Creating Objects Writing and Invoking Constructors Using Methods Defining a Method The Static Methods and Variables Methods with a Variable Number of Parameters JavaBeans Naming Standard for Methods Understanding Enums Inheritance
Khoa CNTT H Nng Lm TP. HCM 01/2007

2/105

Outline

Abstract Classes Writing and Using Interfaces Object-Oriented Relationships The is-a Relationship The has-a Relationship Polymorphism Conversion of Data Types Method Overriding and Overloading Understanding Garbage Collection

Khoa CNTT H Nng Lm TP. HCM 01/2007

3/105

Working with Classes

The class is the basis for object-oriented programming The data and the operations on the data are encapsulated in a class A class is a template that contains the data variables and the methods that operate on those data variables following some logic All the programming activity happens inside classes

Khoa CNTT H Nng Lm TP. HCM 01/2007

4/105

Working with Classes (cont.)

The data variables and the methods in a class are called class members Variables, which hold the data (or point to it in case of reference variables), are said to represent the state of an object The methods constitute class behavior

Khoa CNTT H Nng Lm TP. HCM 01/2007

5/105

The Elements of a class

Khoa CNTT H Nng Lm TP. HCM 01/2007

6/105

Defining Classes
A class is declared by using the keyword class The general syntax for a class declaration is <modifier> class <className> { /**/ }

<className> specifies the name of the class <modifier> specifies some characteristics of the class (optional)

The modifiers group into the following two categories:

Access modifiers: Determine from where the class can be accessed: private, protected, public or default Other modifiers: Specify how the class can be used abstract, final, and strictfp

Khoa CNTT H Nng Lm TP. HCM 01/2007

7/105

Declaring Classes
Element @annotation Class Declaration Elements Function (Optional) An annotation (sometimes called metadata)

public
abstract final class NameOfClass <TypeVariables> extends Super

(Optional) Class is publicly accessible


(Optional) Class cannot be instantiated (Optional) Class cannot be subclassed Name of the class (Optional) Comma-separated list of type variables (Optional) Superclass of the class

implements Interfaces
{

(Optional) Interfaces implemented by the class


Provides the class's functionality

ClassBody

Khoa CNTT H Nng Lm TP. HCM 01/2007

8/105

Declaring Member Variables


Variable Declaration Elements
Element Function (Optional) Access level for the variable (Optional) Declares a class variable

accessLevel

public, protected, private static final

(Optional) Indicates that the variable's value cannot change


(Optional) Indicates that the variable is transient (should not be serialized) (Optional) Indicates that the variable is volatile The type and name of the variable

transient
volatile

type name

Khoa CNTT H Nng Lm TP. HCM 01/2007

9/105

Defining Classes (cont.)


class ClassRoom { private String roomNumber; private int totalSeats = 60; private static int totalRooms = 0; void setRoomNumber(String rn) { roomNumber = rn; } String getRoomNumber() { return roomNumber; } void setTotalSeats(int seats) { totalSeats = seats; } int getTotalSeats() { return totalSeats; } instance variables

class (static) variable

methods

Khoa CNTT H Nng Lm TP. HCM 01/2007

10/105

Controlling Access to Members of a Class


Access Levels Specifier private no specifier protected Y Y Y Class N Y Y Package N N Y Subclass N N N World

public

Y
11/105

Khoa CNTT H Nng Lm TP. HCM 01/2007

Writing and Invoking Constructors

When you instantiate a class, the resulting object is stored in memory. Two elements are involved in allocating and initializing memory for an object in Java: The new operator A special method called a constructor The constructor of a class has the same name as the class and has no explicit return type When the Java runtime system encounters a statement with the new operator, it allocates memory for that instance. Subsequently, it executes the constructor to initialize the memory
Khoa CNTT H Nng Lm TP. HCM 01/2007

12/105

Writing and Invoking Constructors

ComputerLab csLab = new ComputerLab(); When the Java runtime system encounters this statement, it does the following, and in this order:
1. Allocates memory for an instance of class ComputerLab 2. Initializes the instance variables of class ComputerLab 3. Executes the constructor ComputerLab()

Khoa CNTT H Nng Lm TP. HCM 01/2007

13/105

Writing and Invoking Constructors

If you do not provide any constructor for a class you write, the compiler provides the default constructor for that class If you write at least one constructor for the class, the compiler does not provide a constructor In addition to the constructor (with no parameters), you can also define non-default constructors with parameters From inside a constructor of a class, you can call another constructor of the same class You use the keyword this to call another constructor in the same class
Khoa CNTT H Nng Lm TP. HCM 01/2007

14/105

Using Methods

Methods represent operations on data and also hold the logic to determine those operations Using methods offer two main advantages:

A method may be executed (called) repeatedly from different points in the program Methods help make the program logically segmented, or modularized. A modular program is less error prone, and easier to maintain

Khoa CNTT H Nng Lm TP. HCM 01/2007

15/105

Defining a Method

Defining a method in a program is called method declaration A method consists of the following elements:

Name: The name identifies the method and is also used to call (execute) the method. Naming a method is governed by the same rules as those for naming a variable Parameter(s): A method may have zero or more parameters defined in the parentheses Argument(s): The parameter values passed in during the method call Return type: A method may optionally return a value as a result of a method call. Special void return type Access modifier: Each method has a default or specified access modifier
Khoa CNTT H Nng Lm TP. HCM 01/2007

16/105

Defining a Method (cont.)

Syntax

<modifier> <returnType> <methodName> (<Parameters>) { // body of the method. }

Example public int square (int number) { return number*number;Qualified method name: } <objectname>.<methodna Using me> int myNumber = square(2);

Khoa CNTT H Nng Lm TP. HCM 01/2007

17/105

Defining a Method (cont.)


The method name and return type are mandatory in a method declaration Methods and variables visibility:

In a normal case, methods and variables visible only within an instance of the class, and hence each instance has its own copy of those methods and variables Those that are visible from all the instances of the class. Those are called static

Khoa CNTT H Nng Lm TP. HCM 01/2007

18/105

Defining Methods

Access level: public, protected, private Default is package private


Khoa CNTT H Nng Lm TP. HCM 01/2007

19/105

Defining Methods
Element @annotation Function (Optional) An annotation (Optional) Access level for the method (Optional) Declares a class method (Optional) Comma-separated list of type variables. (Optional) Indicates that the method must be implemented in concrete subclasses. (Optional) Indicates that the method cannot be overridden (Optional) Guarantees exclusive access to this method The method's return type and name The list of arguments to the method

accessLevel
static <TypeVariables> abstract final synchronized

returnType methodName
( paramList )

throws exceptions

(Optional) The exceptions thrown by the method


Khoa CNTT H Nng Lm TP. HCM 01/2007

20/105

Creating Objects
Point originOne = new Point(23, 94); Rectangle rectOne = new Rectangle(originOne,100,200); Rectangle rectTwo = new Rectangle(50, 100); Each statement has the following three parts: 1. Declaration: The code set in bold are all variable declarations that associate a variable name with an object type. 2. Instantiation: The new keyword is a Java operator that creates the object. As discussed below, this is also known as instantiating a class. 3. Initialization: The new operator is followed by a call to a constructor. For example, Point(23, 94) is a call to Point's only constructor. The constructor initializes the new object.

Khoa CNTT H Nng Lm TP. HCM 01/2007

21/105

Declaring a Variable to Refer to an Object

type name This notifies the compiler that you will use name to refer to data whose type is type. The Java programming language divides variable types into two main categories: primitive types, and reference types. The declared type matches the class of the object: MyClass myObject = new MyClass(); or MyClass myObject; The declared type is a parent class of the object's class: MyParent myObject = new MyClass(); or MyParent myObject The declared type is an interface which the object's class implements: MyInterface myObject = new MyClass(); or MyInterface myObject A variable in this state, which currently references no object, is said to hold a null reference.
Khoa CNTT H Nng Lm TP. HCM 01/2007

22/105

Initializing an Object
public class Point { public int x = 0; public int y = 0; public Point(int x, int y) { this.x = x; this.y = y; } } Point originOne = new Point(23, 94);

Khoa CNTT H Nng Lm TP. HCM 01/2007

23/105

Initializing an Object
public class Rectangle { public int width; public int height; public Point origin; public Rectangle(Point p, int w, int h) {

origin = p; width = w; height = h;

Rectangle rectOne = new Rectangle(originOne, 100, 200);


Khoa CNTT H Nng Lm TP. HCM 01/2007

24/105

Using Objects
You can use an object in one of two ways: Directly manipulate or inspect its variables Call its methods Referencing an Object's Variables The following is known as a qualified name: objectReference.variableName System.out.println("Width of rectOne: " + rectOne.width); System.out.println("Height of rectOne: " + rectOne.height); int height = new Rectangle().height; Calling an Object's Methods objectReference.methodName(); or objectReference.methodName(argumentList); System.out.println("Area of rectOne: " + rectOne.area()); rectTwo.move(40, 72);

Khoa CNTT H Nng Lm TP. HCM 01/2007

25/105

The Static Methods and Variables


The static modifier may be applied to a variable, a method, and a block of code A static element of a class is visible to all the instances of the class If one instance makes a change to it, all the instances see that change A static variable is initialized when a class is loaded, An instance variable is initialized when an instance of the class is created A static method also belongs to the class, and not to a specific instance of the class Therefore, a static method can only access the static members of the class.
Khoa CNTT H Nng Lm TP. HCM 01/2007

26/105

class StaticCodeExample { static int counter=0; static { counter++; System.out.println("Static Code block: counter: " + counter); } StaticCodeExample() { System.out.println("Construtor: counter: " + counter); } } public class RunStaticCodeExample { public static void main(String[] args) { StaticCodeExample sce = new StaticCodeExample(); System.out.println("main: counter:" + sce.counter); } }
Khoa CNTT H Nng Lm TP. HCM 01/2007

27/105

The Static Methods

A method declared static in a class cannot access the non static variables and methods of the class A static method can be called even before a single instance of the class exists Static method main(), which is the entry point for the application execution It is executed without instantiating the class in which it exists

Khoa CNTT H Nng Lm TP. HCM 01/2007

28/105

class MyClass { String salute = "Hello"; public static void main(String[] args){ System.out.println("Salute: " + salute); } } Error: Cannot access a non

static variable from inside a static method

Khoa CNTT H Nng Lm TP. HCM 01/2007

29/105

Understanding Instance and Class Members


public class AClass { public int instanceInteger = 0; public int instanceMethod() { return instanceInteger; } public static int classInteger = 0; public static int classMethod() { return classInteger; }

public static void main(String[] args) { AClass anInstance = new AClass(); AClass anotherInstance = new AClass();
Khoa CNTT H Nng Lm TP. HCM 01/2007

30/105

Understanding Instance and Class Members


//Refer to instance members through an instance. anInstance.instanceInteger = 1; anotherInstance.instanceInteger = 2; System.out.println("Instance method 1: " + anInstance.instanceMethod()); System.out.println("Instance method 2: " + anotherInstance.instanceMethod());

//Illegal to refer directly to instance members from a class method //System.out.println("Instance method 1: " + instanceMethod()); //System.out.println("Instance method 2: " + instanceInteger);

Khoa CNTT H Nng Lm TP. HCM 01/2007

31/105

Understanding Instance and Class Members


//Refer to class members through the class... AClass.classInteger = 7; System.out.println("Class method: " +classMethod());

//...or through an instance. (Possible but not generally recommended.) System.out.println("Class method from an Instance:" +
anInstance.classMethod()); //Instances share class variables anInstance.classInteger = 9; System.out.println("Class method from an Instance1:" + anInstance.classMethod()); System.out.println("Class method from an Instance2:" + anotherInstance.classMethod()); }
Khoa CNTT H Nng Lm TP. HCM 01/2007

32/105

Initializing Instance and Class Members Using Static Initialization Blocks import java.util.*; class Errors { static ResourceBundle errorStrings; static { try { errorStrings = ResourceBundle.getBundle("ErrorStrings"); } catch (MissingResourceException e) { //error recovery code here

} } }

Khoa CNTT H Nng Lm TP. HCM 01/2007

33/105

Initializing Instance and Class Members

Using Static Initialization Blocks

import java.util.*; class Errors { static ResourceBundle errorStrings = initErrorStrings(); private static ResourceBundle initErrorStrings() { try { return ResourceBundle.getBundle("ErrorStrings"); } catch (MissingResourceException e) { //error recovery code here } } }
Khoa CNTT H Nng Lm TP. HCM 01/2007

34/105

Exercise
public class StringAnalyzer2 { private String origin; private String delimiter; public StringAnalyzer2(String origin, String delimiter){ ...... } public boolean hasMoreElement(){ ...... } public String getNextElement(){ ...... } }

Khoa CNTT H Nng Lm TP. HCM 01/2007

35/105

Using Modifiers

You cannot specify any modifier for the variables inside a method You cannot specify the protected modifier for a top-level class A method cannot be overridden to be less public.

Khoa CNTT H Nng Lm TP. HCM 01/2007

36/105

Understanding Using Modifiers

The final Modifier The final modifier may be applied to a class, a method, or a variable. It means, in general, that the element is final If the element declared final is a variable, that means the value of the variable is constant, and cannot be changed If a class is declared final, it means the class cannot be extended If a final method cannot be overridden

Khoa CNTT H Nng Lm TP. HCM 01/2007

37/105

Understanding Using Modifiers


class Calculator { final int dime = 10; int count = 0; Calculator (int i) { count = i; } } Error: calc is final class RunCalculator { public static void main(String[] args) { final Calculator calc = new Calculator(1); calc = new Calculator(2); OK: default access calc.count = 2; calc.dime = 11; Error: dime is final System.out.println("dime: " + calc.dime); } }
Khoa CNTT H Nng Lm TP. HCM 01/2007

38/105

Understanding Using Modifiers

The native Modifier In your applications, sometimes you will want to use a method that exists outside of the JVM The native modifier can only apply to a method The native method is usually implemented in a non-Java language such as C or C++ Before a native method can be invoked, a library that contains the method must be loaded. The library is loaded by making the following system call: System.loadLibrary("<libraryName>");
Khoa CNTT H Nng Lm TP. HCM 01/2007

39/105

Understanding Using Modifiers


class MyNativeExample { native void myNativeMethod(); static { System.loadLibrary("NativeMethodLib"); } }

Khoa CNTT H Nng Lm TP. HCM 01/2007

40/105

Understanding Using Modifiers

The transient Modifier

an object may be stored in persistent storage (say disk) outside of the JVM, for later use by the same application, or by a different application The process of storing an object is called serialization For an object to be serializable.The corresponding class must implement the interface Serializable, or Externalizable A variable declared transient is not stored The transient modifier can only be applied to instance variables
Khoa CNTT H Nng Lm TP. HCM 01/2007

41/105

Methods with a Variable Number of Parameters

A new feature in J2SE 5.0 that lets you define methods with a variable number of parameters You can make several method calls with a variable number of arguments These are also called variable-length argument methods

Khoa CNTT H Nng Lm TP. HCM 01/2007

42/105

Methods with a Variable Number of Parameters Syntax There must be ony one variable-length parameters list If there are individual parameters in addition to the list, the variable-length parameters list must appear last inside the parentheses of the method The variable-length parameters list consists of a type followed by three dots and the name Example public void printStuff (String greet, int... values)

Khoa CNTT H Nng Lm TP. HCM 01/2007

43/105

Methods with a Variable Number of Parameters


import java.io.*; class MyClass { public void printStuff(String greet, int... values) { for (int v : values ) { System.out.println( greet + ":" + v); } } } class VarargTest { public static void main(String[] args) { MyClass mc = new MyClass(); mc.printStuff("Hello", 1); mc.printStuff("Hey", 1,2); mc.printStuff("Hey you", 1,2,3); } }
Khoa CNTT H Nng Lm TP. HCM 01/2007

44/105

Methods with a Variable Number of Parameters

public void printStuff (int... values, String greet)


Error: variable-length parameter must appear at the last public void printStuff (String greet, int... values, double dnum) Method has at most one variable length parameter

Khoa CNTT H Nng Lm TP. HCM 01/2007

45/105

Passing Arguments into Methods

Assume you declare a variable in your method, and then you pass that variable as an argument in a method call The question is: What kind of effect can the called method have on the variable in your method? There are two kind: pass-by-value pass-by-reference

Khoa CNTT H Nng Lm TP. HCM 01/2007

46/105

Passing a Primitive Variable

When a primitive variable is passed as an argument in a method call, only the copy of the original variable is passed Any change to the passed variable in the called method will not affect the variable in the calling method It is called pass-by-value

Khoa CNTT H Nng Lm TP. HCM 01/2007

47/105

Passing Primitive Variables


public class SwapNumber extends TestCase{ public void swap(int a, int b){ int c = a; a = b; b = c; } public void test(){ int a = 1, b = 2; System.out.println("Before swap a: "+ a + " , b: "+b); swap(a,b); System.out.println("After swap a: "+ a + " , b: "+b); } }

Khoa CNTT H Nng Lm TP. HCM 01/2007

48/105

Passing Primitive Variables


public class SwapNumber extends TestCase{ public void swap(Integer a1, Integer b1){ Integer c = a1; a1 = b1; b1 = c; } public void test(){ Integer a = new Integer (1), b = new Integer (2); System.out.println("Before swap a: "+ a + " , b: "+b); swap(a,b); System.out.println("After swap a: "+ a + " , b: "+b); } }
Khoa CNTT H Nng Lm TP. HCM 01/2007

49/105

Passing Object Reference Variables

When you pass an object variable into a method, you must keep in mind that you're passing the object reference, and not the actual object itself.

import java.awt.Dimension;

class ReferenceTest { public static void main (String [] args) { Dimension d = new Dimension(5,10); ReferenceTest rt = new ReferenceTest(); System.out.println("Before modify() d.height = "+ d.height); rt.modify(d); System.out.println("After modify() d.height = "+ d.height); } void modify(Dimension dim) { dim.height = dim.height + 1; System.out.println("dim = " + dim.height); } }
Khoa CNTT H Nng Lm TP. HCM 01/2007

50/105

Passing Object Reference Variables

Before modify() d.height = 10 dim = 11 After modify() d.height = 11

Khoa CNTT H Nng Lm TP. HCM 01/2007

51/105

Passing Object Reference Variables


public class PassingVar extends TestCase{ public void modify(Student st){ st.setName("Tran Thi B"); st = new Student("Le Van C"); } public void test() { Student sv1 = new Student("Nguyen Van A"); System.out.println("Before modify():"+sv1); modify(sv1); System.out.println("After modify():"+sv1); }

Before modify():Nguyen Van A After modify():Tran Thi B


Khoa CNTT H Nng Lm TP. HCM 01/2007

52/105

Passing a Reference Variable

When you pass a reference variable in a method, you pass a copy of it and not the original reference variable The called method can change the object properties by using the passed reference Changing the object and the reference to the object are two different things, so note the following: The original object can be changed in the called method by using the passed reference to the object However, if the passed reference itself is changed in the called method, for example, set to null or reassigned to another object, it has no effect on the original reference variable in the calling method
Khoa CNTT H Nng Lm TP. HCM 01/2007

53/105

JavaBeans Naming Standard for Methods

Methods can be used to set the values of the class variables and to retrieve the values Methods written for these specific purposes are called get and set methods (also known as getter and setter) In special Java classes, called JavaBeans, the rules for naming the methods (including get and set) are enforced as a standard The private variables of a JavaBean called properties can only be accessed through its getter and setter methods

Khoa CNTT H Nng Lm TP. HCM 01/2007

54/105

JavaBeans Naming Standard for Methods

The rules The naming convention for a property is: the first letter of the first word in the name must be lowercase and the first letter of any subsequent word in the name must be uppercase, e.g., myCow The name of the getter method begins with get followed by the name of the property, with the first letter of each word uppercased A getter method does not have any parameter and its return type matches the argument type The setter method begins with set followed by the name of the property, with the first letter of each word uppercased A setter method must have the void return type The getter and setter methods must be public
Khoa CNTT H Nng Lm TP. HCM 01/2007

55/105

JavaBeans Naming Standard for Methods


public class ScoreBean { private double meanScore; // getter method for property meanScore public double getMeanScore() { return meanScore; } // setter method to set the value of the property meanScore public void setMeanScore(double score) { meanScore = score; } }

Khoa CNTT H Nng Lm TP. HCM 01/2007

56/105

Understanding Enums

enum type defines a set of constants that are represented as unique identifiers Like classes, all enum types are reference types, which means that you can refer to an object of an enum type with a reference An enum type is declared with an enum declaration, which is a comma-separated list of enum constants the declaration may optionally include other components of traditional classes, such as constructors, fields and methods

Khoa CNTT H Nng Lm TP. HCM 01/2007

57/105

Understanding Enums (cont.)

Each enum declaration declares an enum class with the following restrictions: enum types are implicitly final, because they declare constants that should not be modified enum constants are implicitly static Any attempt to create an object of an enum type with operator new results in a compilation error The enum constants can be used anywhere constants can be used, such as in the case labels of switch statements and to control enhanced for statements

Khoa CNTT H Nng Lm TP. HCM 01/2007

58/105

public enum Book{ // declare constants of enum type JHTP6( "Java How to Program 6e", "2005" ), CHTP4( "C How to Program 4e", "2004" ), IW3HTP3( "Internet & World Wide Web", "2004" ), CPPHTP4( "C++ How to Program 4e", "2003" ), VBHTP2( "Visual Basic .NET How to Program 2e", "2002" ), CSHARPHTP( "C# How to Program", "2002" ); // instance fields private final String title; // book title private final String copyrightYear; // copyright year // enum constructor Book( String bookTitle, String year ){ title = bookTitle; copyrightYear = year; } // accessor for field title public String getTitle(){ return title; } // accessor for field copyrightYear public String getCopyrightYear(){ return copyrightYear; } Khoa CNTT H Nng Lm TP. HCM 01/2007

59/105

import java.util.EnumSet; public class EnumTest { public static void main( String args[] ) { System.out.println( "All books:\n" ); // print all books in enum Book for ( Book book : Book.values() ) System.out.println(book + + book.getTitle() + + book.getCopyrightYear() ); System.out.println( "\nDisplay a range of enum constants:\n" ); // print first four books for ( Book book : EnumSet.range( Book.JHTP6, Book.CPPHTP4 ) ) System.out.println( book + + book.getTitle() + + book.getCopyrightYear() );

Khoa CNTT H Nng Lm TP. HCM 01/2007

60/105

Inheritance

Inheritance is a fundamental feature of objectoriented programming It enables the programmer to write a class based on an already existing class The already existing class is called the parent class, or superclass The new class is called the subclass, or derived class The subclass inherits (reuses) the nonprivate members (methods and variables) of the superclass, and may define its own members as well
Khoa CNTT H Nng Lm TP. HCM 01/2007

61/105

Inheritance (cont.)
Inheritance facilitates the reuse of code and helps to adapt programming to real-world situations The keyword to derive a class from another class is extends class ComputerLab extends ClassRoom { } All java classes derive from built-in java class Object A class can inherit only from one other class and no more. This is called single inheritance Special keyword super refer to superclass

Khoa CNTT H Nng Lm TP. HCM 01/2007

62/105

Inheritance (cont.)
class ComputerLab extends ClassRoom { int totalComputers = 30; String labAssistant="TBA"; void printSeatInfo() { System.out.println("There are " + getTotalSeats() + " seats, and + totalComputers + " computers in this computer lab."); } String getLabAssistant(){ return labAssistant; } void setLabAssistant(String assistant){ this.labAssistant = assistant; } }
Khoa CNTT H Nng Lm TP. HCM 01/2007

63/105

Abstract Classes

A class that is declared abstract cannot be instantiated Instantiation of an abstract class is not allowed, because it is not fully implemented yet Declare class is abstract by using abstract modifier The abstract modifier may be applied to a class or a method

Khoa CNTT H Nng Lm TP. HCM 01/2007

64/105

Abstract Classes (cont.)

A abstract class may have one or more abstract methods in any of the following ways: The class may have one or more abstract methods originally defined in it The class may have inherited one or more abstract methods from its superclass, and has not provided implementation for all or some of them. The class declares that it implements an interface, but does not provide implementation for at least one method in the interface if there is no abstract method in the class, it could still be declared abstract
Khoa CNTT H Nng Lm TP. HCM 01/2007

65/105

Abstract Classes (cont.)


abstract class Shape { abstract void draw(); //Note that there are no curly braces here. void message() { System.out.println("I cannot live without being a parent."); } } class Circle extends Shape { void draw() { System.out.println("Circle drawn."); } }

Khoa CNTT H Nng Lm TP. HCM 01/2007

66/105

Abstract Classes (cont.)


class Cone extends Shape { void draw() { System.out.println("Cone drawn."); } } public class RunShape { public static void main(String[] args) { Circle circ = new Circle(); Cone cone = new Cone(); circ.draw(); cone.draw(); cone.message(); } }

Khoa CNTT H Nng Lm TP. HCM 01/2007

67/105

Writing and Using Interfaces


Java supports single inheritance. That means a subclass in Java can have only one superclass However, if multiple inheritance is needed ? Java provides a solution: use an interface A subclass can also inherit from one or more interfaces in addition to the superclass An interface is a template that contains some method declarations. The interface provides only declarations for the methods, and no implementation The class that inherits from an interface must provide the implementation for the methods declared in the interface
Khoa CNTT H Nng Lm TP. HCM 01/2007

68/105

What is an Interface

An interface defines: a protocol of behavior that can be implemented by any class anywhere in the class hierarchy; a set of methods but does not implement them. A class that implements the interface agrees to implement all the methods defined in the interface, thereby agreeing to certain behavior. Definition: An interface is a named collection of method definitions, without implementations.

Khoa CNTT H Nng Lm TP. HCM 01/2007

69/105

What is an Interface

Because an interface is simply a list of unimplemented, and therefore abstract, methods, you might wonder how an interface differs from an abstract class. The differences are significant. An interface cannot implement any methods, whereas an abstract class can. A class can implement many interfaces but can have only one superclass. abstract class can define both abstract and nonabstract methods, an interface can have only abstract methods An interface is not part of the class hierarchy. Unrelated classes can implement the same interface.
Khoa CNTT H Nng Lm TP. HCM 01/2007

70/105

Interface Characteristics

All interface methods are implicitly public and abstract. In other words, you do not need to actually type the public or abstract modifiers in the method declaration, but the method is still always public and abstract. All variables defined in an interface must be public, static, and final in other words, interfaces can declare only constants, not instance variables. Interface methods must not be static. Because interface methods are abstract, they cannot be marked final, static, or native. An interface can extend one or more other interfaces. An interface cannot extend anything but another interface. An interface cannot implement another interface or class. An interface must be declared with the keyword interface. Interface types can be used polymorphically
Khoa CNTT H Nng Lm TP. HCM 01/2007

71/105

Declaring Interface Constants

interface Foo { int BAR = 42; void go(); class Zap implements Foo { public void go() { BAR = 27; }

} //what is a bug?
Khoa CNTT H Nng Lm TP. HCM 01/2007

72/105

Declaring Interface Constants

Look for interface definitions that define constants, but without explicitly using the required modifiers. For example, the following are all identical. public int x = 1; // Looks non-static and non-final, but isn't! int x = 1; // Looks default, non-final, non-static, but isn't! static int x = 1; // Doesn't show final or public final int x = 1; // Doesn't show static or public public static int x = 1; // Doesn't show final public final int x = 1; // Doesn't show static static final int x = 1; // Doesn't show public public static final int x = 1; // what you get implicitly

Khoa CNTT H Nng Lm TP. HCM 01/2007

73/105

Steps in using a Interface

define an INTERFACE that defines the method header for the desired method, declare in each class that defines this method that it IMPLEMENTS THE INTERFACE and CAST the object that invokes the desired method to be of the type for which the desired method is defined.

Khoa CNTT H Nng Lm TP. HCM 01/2007

74/105

Implementing an Interface
class Foo { } class Bar implements Foo { } interface Baz { } interface Fi { } interface Fee implements Baz { //OK //No! Can't implement a class //OK // OK } //No! Interface can't // implement an interface interface Zee implements Foo { } //No! Interface can't // implement a class interface Zoo extends Foo { } //No! Interface can't // extend a class interface Boo extends Fi { } // OK. Interface can extend // an interface class Toon extends Foo, Button { } //No! Class can't extend // multiple classes class Zoom implements Fi, Fee { } // OK. class can implement // multiple interfaces interface Vroom extends Fi, Fee { } // OK. interface can extend // multiple interfaces class Yow extends Foo implements Fi { } // OK. Class can do //both (extends must be 1st)
Khoa CNTT H Nng Lm TP. HCM 01/2007

75/105

Writing and Using Interfaces (cont.)


define an interface by the keyword interface interface <InterfaceName> { <dataType1> <var1>; <dataType2> <var2>; <ReturnType1> <methodName1> ( ); <ReturnType2> <methodName2>(<parameters>); } // interface definition ends here. The methods declared in an interface are implicitly public and abstract All interface variables are inherently public, static, and final An interface cannot implement any interface or class

Khoa CNTT H Nng Lm TP. HCM 01/2007

76/105

Writing and Using Interfaces (cont.)


interface ParentOne { int pOne = 1; void printParentOne(); } interface ParentTwo { int pTwo = 2; void printParentTwo(); } interface Child extends ParentOne, ParentTwo{ int child = 3; void printChild(); }
Khoa CNTT H Nng Lm TP. HCM 01/2007

77/105

Writing and Using Interfaces (cont.)


class InheritClass implements Child { public void printParentOne(){ System.out.println(pOne); } public void printParentTwo(){ System.out.println(pTwo); } public void printChild(){ System.out.println(child); } } class TestInterface { public static void main(String[] args){ InheritClass ic = new InheritClass(); ic.printParentOne(); ic.printParentTwo(); ic.printChild(); } }
Khoa CNTT H Nng Lm TP. HCM 01/2007

78/105

Implement a Sorted list with Interface


Consider the following problem The bookstore manager would like to have a list of books ordered by the published year. The runner would like to have a list of entries ordered

by the date

We need to develop the method sort in the class AList and its derived classes.

abstract public AList sort();

Khoa CNTT H Nng Lm TP. HCM 01/2007

79/105

Implement a Sorted list with Interface


Book b1 = new Book("HtDP", 2000, 55); Book b2 = new Book("Call of the Wild", 1995, 10); Book b3 = new Book("The Sea-Wolf", 1999, 12); AList mtlist = new MTList(); AList blist1 = new List(b3, new MTList()); AList blist2 = new List(b1, new List(b2, new List(b3, new MTList())))); mtlist.sort(); // should be new MTList() blist1.sort(); // should be new List(b3, new MTList()); blist2.sort(); // should be new List(b2, new List(b3, new List(b1, new MTList()))));
80/105

Khoa CNTT H Nng Lm TP. HCM 01/2007

Implement a Sorted list with Interface


We need to complete the method insert. // in the class MTList : insert the given book into this sorted list of books AList insert(Object b){ return new List(b, this); } // to create from this list a new list sorted by the year published AList sort(){ return this;} // in the class List : insert the given book into this sorted list of books AList insert(Object b){ if ( b < this.first) return(new List(b, this)); else return(new List(this.first, this.rst.insert(b))); } // to create from this list a new list sorted by the year published AList sort(){ return (this.rest.sort()).insert(this.fist); }
Khoa CNTT H Nng Lm TP. HCM 01/2007

81/105

A Problem in the object comparing


This Object is smaller than other Object This Object is the same as other Object This Object is greater than other Object How do you do it?

Khoa CNTT H Nng Lm TP. HCM 01/2007

82/105

The Interface Comparable<T>


interface Comparable<T>{ // compare this object with the given object // produce negative result if this is 'smaller' than the given object // produce zero if this object is 'the same' as the given object // produce positive result if this is 'greater' than the given object int compareTo(T obj); }

Khoa CNTT H Nng Lm TP. HCM 01/2007

83/105

Using the Comparable Interface


public class Entry implements IValuable, Comparable<Entry>{ private Date date; private String comment; private double distance; private int duration; // compare the date recorded in this entry with the given entry public int compareTo( Entry obj) { return this.date.getDate() obj.date.getDate(); } }
Khoa CNTT H Nng Lm TP. HCM 01/2007

84/105

Using the Comparable Interface


public class Book implements IValuable, Comparable< Book >{ private Author author; private String title; private double cost; private int publishYear; // compare the publication year of this book with the given book public int compareTo( Book obj) { return this.publishYear - obj.publishYear; } }

Khoa CNTT H Nng Lm TP. HCM 01/2007

85/105

Using the Comparable Interface


public class List extends AList {

private Object first; private AList rest; public List(Object first, AList rest) { this.first = first; this.rest = rest; } public AList sort() { return this.rest.sort().insert(this.first); } public String toString() { return "" + first + rest; } AList insert(Object obj) { if (((Comparable)this.first).compareTo(obj) > 0) return(new List(obj, this)); else return(new List(this.first, this.rest.insert(obj))); }}
Khoa CNTT H Nng Lm TP. HCM 01/2007

86/105

Objects that represent functions interface Comparator{ int compare(Object obj1, Object obj2); }

Khoa CNTT H Nng Lm TP. HCM 01/2007

87/105

Object-Oriented Relationships

In an application, the classes and class members are related to each other A class has a data variable defined in it The classes themselves are related to each other A class is derived from another class There are two kinds of relationships that the classes inside an application may have, and these kinds correspond to the two properties of classes: Inheritance (is-a relationship) Data abstraction (has-a relationship)

Khoa CNTT H Nng Lm TP. HCM 01/2007

88/105

The is-a Relationship


class Stereo { }
a boombox is a stereo

class Boombox extends Stereo { } A rule of thumb to recognize an is-a relationship is that every object of the subclass is also an object of the superclass and not vice versa

Khoa CNTT H Nng Lm TP. HCM 01/2007

89/105

The has-a Relationship

The has-a relationship corresponds to an objectoriented characteristic called encapsulation, which means the data and the methods are combined into a structure called a class

class Stereo { } class Boombox extends Stereo { CDPlayer cdPlayer = new CDPlayer(); } the boombox is-a stereo class CDPlayer { and it has-a CD player }
Khoa CNTT H Nng Lm TP. HCM 01/2007

90/105

Polymorphism

The is-a relationship between a superclass and a subclass has a profound implication

a cow is an animal means that all cows are animals It further means that you can substitute an object of the subclass Cow for an object of the superclass Animal, because a cow is an animal

Animal a = new Animal(); a = new Cow(); // Now, a points to an object of Cow

Khoa CNTT H Nng Lm TP. HCM 01/2007

91/105

Polymorphism (cont.)

Now, a superclass can have multiple subclasses. if a cow is an animal so is a buffalo This means you can substitute either a cow or a buffalo for an animal This is an example of polymorphism, which means giving different meaning to the same thing

Khoa CNTT H Nng Lm TP. HCM 01/2007

92/105

Polymorphism (cont.)
class Animal { public void saySomething() { System.out.println("Umm..."); } } class Cow extends Animal { public void saySomething() { // super.saySomething(); System.out.println("Moo!"); } } class Buffalo extends Animal{ public void saySomething() { // super.saySomething(); System.out.println("Bah!"); } Khoa CNTT H Nng Lm TP. HCM 01/2007 }

93/105

Polymorphism (cont.)
public class TestPoly { public static void main(String [] args) { Animal heyAnimal = new Animal(); Cow c = new Cow(); Buffalo b = new Buffalo(); heyAnimal.saySomething(); heyAnimal=c; heyAnimal.saySomething(); heyAnimal=b; heyAnimal.saySomething(); } }

Khoa CNTT H Nng Lm TP. HCM 01/2007

94/105

Polymorphism (cont.)

The compiler only knows about the declared object reference types. However, at runtime, the JVM knows what the referred object really is Polymorphism does not apply to the static class members The capability to convert an object reference from one type to another type is at the heart of polymorphism

Khoa CNTT H Nng Lm TP. HCM 01/2007

95/105

Conversion of Data Types

Two kinds of Conversion of Data Types Conversion of Primitive Data Types Conversion of Reference Data Types Conversion of Data Types Implicit type conversion: The programmer does not make any attempt to convert the type Explicit type conversion: Conversion is initiated by the programmer by making an explicit request for conversion (type casting)

Khoa CNTT H Nng Lm TP. HCM 01/2007

96/105

Assignment Conversion <sourceType> s = new <sourceType>(); <targetType> t = s; // Implicit conversion of <sourceType> to <targetType> Method Call Conversion Arithmetic Conversion

Khoa CNTT H Nng Lm TP. HCM 01/2007

97/105

Implicit Primitive Type Conversion

Two general rules for implicit primitive type conversion are the following:

There is no conversion between boolean and nonboolean types. A non-boolean type can be converted into another nonboolean type only if the conversion is not narrowing that is, the size of the target type is greater than or equal to the size of the source type.

Khoa CNTT H Nng Lm TP. HCM 01/2007

98/105

Implicit Primitive Type Conversion


public class ConversionToWider{ public static void main(String[] args) { int i = 15; short s = 10; Error: Illegal conversion i = s; System.out.println("Value of i: " + i ); } }

Khoa CNTT H Nng Lm TP. HCM 01/2007

99/105

Implicit Primitive Type Conversion

Khoa CNTT H Nng Lm TP. HCM 01/2007

100/105

Explicit Primitive Type Conversion


In a narrowing conversion, casting is mandatory However, casting to a narrower type runs the risk of losing information and generating inaccurate results You cannot cast a boolean to a non-boolean type. You cannot cast a non-boolean type to a boolean type.

Khoa CNTT H Nng Lm TP. HCM 01/2007

101/105

Implicit Object Reference Types Conversion

there are three kinds of object reference types:


A class An interface An array

Khoa CNTT H Nng Lm TP. HCM 01/2007

102/105

Implicit Object Reference Types Conversion

A class type may be converted to another class type if one of the following is true: The <sourceType>is a subclass of the <targetType>. The <sourceType>implements the <targetType>. An interface type may be converted to one of the following: Another interface if the <sourceType>is a subinterface of the <targetType>. The Objecttype if the <targetType>is an object. An array may be converted to one of the following: Another array if the following conditions are true: both <sourceType>and <targetType> are arrays of object reference types, and the object reference type of <sourceType>array elements is convertible to the object reference types of <targetType>array elements. The interface: Cloneable or Serializable. The class Object.
Khoa CNTT H Nng Lm TP. HCM 01/2007

103/105

Explicit Object Reference Types Conversion

Two level of conversion


At compile time, the following rules must be obeyed:


Compile time Run Time

When both the source type and target type are classes, one class must be a subclass of the other. When both the source type and target type are arrays, the elements of both the arrays must be object reference types and not primitive types. Also, the object reference type of the source array must be convertible to the object reference type of the target array. The casting between an interface and an object that is not final is always allowed.
Khoa CNTT H Nng Lm TP. HCM 01/2007

104/105

Explicit Object Reference Types Conversion

If a casting passes the compilation, then the following rules are enforced at runtime: If the target type is a class, then the class of the expression being converted must be either the same as the target type or its subclass. If the target type is an interface, then the class of the expression being converted must implement the target type.

Khoa CNTT H Nng Lm TP. HCM 01/2007

105/105

Explicit Object Reference Types Conversion Auditorium a1,a2; ClassRoom c; LectureHall lh; a1 = new Auditorium();

OK: implicit conversion c = a1; OK: explicit conversion a2 = (Auditorium) c; Error: illegal conversion lh = (LectureHall) c;
Khoa CNTT H Nng Lm TP. HCM 01/2007

106/105

Method Overriding and Overloading

Method Overriding method overriding is a feature of Java that lets the programmer declare and implement a method in a subclass that has the same signature as a method in the superclass Rules for method overriding You cannot override a method that has the final modifier. You cannot override a static method to make it non-static. The overriding method and the overridden method must have the same return type. J2SE 5 allows a covariant return type as well The number of parameters and their types in the overriding method must be same as in the overridden method and the types must appear in the same order. However, the names of the parameters may be different.

Khoa CNTT H Nng Lm TP. HCM 01/2007

107/105

Overloading (cont.)

Rules for method overriding (cont.)


You cannot override a method to make it less accessible. If the overriding method has a throws clause in its declaration, then the following two conditions must be true:

The overridden method must have a throws clause, as well. Each exception included in the throws clause of the overriding method must be either one of the exceptions in the throws clause of the overridden method or a subclass of it.

If the overridden method has a throws clause, the overriding method does not have to.

Khoa CNTT H Nng Lm TP. HCM 01/2007

108/105

Overloading (cont.)

A covariant return type of an overriding method is a subclass of the return type of the overridden method, and is legal

public Number myMethod(); public Double myMethod(); OK: Covariant return type public int myMethod(); Error: Difference return public double myMethod(); type

Khoa CNTT H Nng Lm TP. HCM 01/2007

109/105

Overloading (cont.)

Method Overloading

Method overloading is a feature of Java that facilitates defining multiple methods in a class with identical name Method overloading may have difference return type A constructor of a class has the same name as the class, and has no explicit return type; it can have zero or more parameters A class may have more than one constructor. If the programmer defines no constructor in a class, the compiler adds the default constructor with no arguments. If one or more constructors are defined in the class, the compiler does not provide any constructor

Constructor Overloading

Khoa CNTT H Nng Lm TP. HCM 01/2007

110/105

Understanding Garbage Collection

The process of freeing memory from the used objects is called garbage collection. How do you accomplish this in Java?

In Java, garbage collection is done automatically by what is called the garbage collector

The garbage collector in Java automates memory management by freeing up the memory from objects that are no longer in use

The advantage of this is that you do not need to code the memory management into your application The price you pay for this service is that you have no control over when the garbage collector run

Khoa CNTT H Nng Lm TP. HCM 01/2007

111/105

Collection (cont.)

There are two things that you can do in the code to help memory management:

Make an object eligible for garbage collection, because a garbage collector will only free up memory from an eligible object. Make a request for garbage collection by making a system call to the garbage collector: System.gc(); You can also invoke the gc() method by using an instance of the Runtime class

Khoa CNTT H Nng Lm TP. HCM 01/2007

112/105

Collection (cont.)
class RuntimeTest { public static void main (String [] args) { Runtime rt = Runtime.getRuntime(); System.out.println("JVM free memory before + running gc: " + rt.freeMemory()); rt.gc(); System.out.println("JVM free memory after+ running gc: " + rt.freeMemory()); } }

Khoa CNTT H Nng Lm TP. HCM 01/2007

113/105

Collection (cont.)

A call to the garbage collector is no guarantee that the memory will be free The basic requirement for garbage collection is that you must make your object eligible for garbage collection

You can remove the references to an object in two ways:


An object is considered eligible for garbage collection when there is no reference pointing to it
Set the object reference variable pointing to the object to null Reassign a reference variable of an object to another object

Khoa CNTT H Nng Lm TP. HCM 01/2007

114/105

finalize() Method

What if you want an object to clean up its state before it is deleted?


You can declare the finalize() method in the class This method will be called by the garbage collector before deleting any object of this class

The finalize() method is inherited from the Object class The signature of the finalize() protected void finalize() Remember that the finalize() method that your class inherited does not do anything

Khoa CNTT H Nng Lm TP. HCM 01/2007

115/105

finalize() Method (cont.)


protected void finalize() { super.finlaize(); // clean up code follows. }

Khoa CNTT H Nng Lm TP. HCM 01/2007

116/105

OBJECT BASICS

Cleaning Up Unused Objects

The Java platform allows you to create as many objects as you want (limited, of course, by what your system can handle), and you don't have to worry about destroying them. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection. An object is eligible for garbage collection when there are no more references to that object. The Java runtime environment has a garbage collector that periodically frees the memory used by objects that are no longer referenced. The garbage collector does its job automatically when it determines that the time is right.
Khoa CNTT H Nng Lm TP. HCM 01/2007

118/105

Cleaning Up: Nulling a Reference


The first way to remove a reference to an object is to set the reference variable that refers to the object to null. public class GarbageTruck { public static void main(String [] args) { StringBuffer sb = new StringBuffer("hello"); System.out.println(sb);
// The StringBuffer object is not eligible for collection

sb = null;
// Now the StringBuffer object is eligible for collection

Khoa CNTT H Nng Lm TP. HCM 01/2007

119/105

Cleaning Up: Reassigning a Reference Variable

class GarbageTruck { public static void main(String [] args) { StringBuffer s1 = new StringBuffer("hello"); StringBuffer s2 = new StringBuffer("goodbye"); System.out.println(s1); s1 = s2;

// At this point the StringBuffer "hello" is not eligible

// Redirects s1 to refer to the "goodbye" object // Now the StringBuffer "hello" is eligible for collection

Khoa CNTT H Nng Lm TP. HCM 01/2007

120/105

Cleaning Up:Reassigning a Reference Variable import java.util.Date; public class GarbageFactory { public static Date getDate() { Date d2 = new Date(); StringBuffer now = new StringBuffer(d2.toString()); System.out.println(now); return d2; } public static void main(String [] args) { Date d = getDate(); doComplicatedStuff(); System.out.println("d = " + d) ; } }
Khoa CNTT H Nng Lm TP. HCM 01/2007

121/105

Cleaning Up: Isolating a Reference

Khoa CNTT H Nng Lm TP. HCM 01/2007

122/105

Cleaning Up: Forcing Garbage Collection


import java.util.Date; public class CheckGC { public static void main(String [] args) { Runtime rt = Runtime.getRuntime(); System.out.println("Total JVM memory: " + rt.totalMemory()); System.out.println("Before Memory = " + rt.freeMemory()); Date d = null; for(int i = 0; i<10000; i++) { d = new Date () ; d = null; } System.out.println("After Memory = " + rt.freeMemory()); rt.gc(); // an alternate to System.gc() System.out.println("After GC Memory = " + rt.freeMemory()); } }
Khoa CNTT H Nng Lm TP. HCM 01/2007

123/105

Cleaning up before Garbage Collection The finalize() Method Java provides you a mechanism to run some code just before your object is deleted by the garbage collector. This code is located in a method named finalize() that all classes inherit from class Object. On the surface this sounds like a great idea; maybe your object opened up some resources, and you'd like to close them before your object is deleted. The problem is that, as you may have gathered by now, you can't count on the garbage collector to ever delete an object. So, any code that you put into your class's overridden finalize() method is not guaranteed to run. The finalize() method for any given object might run, but you can't count on it, so don't put any essential code into your finalize() method. In fact, we recommend that in general you don't override finalize() at all
Khoa CNTT H Nng Lm TP. HCM 01/2007

124/105

Some important points about finalizers:

If an object has a finalizer, the finalizer method is invoked sometime after the object becomes unused (or unreachable), but before the garbage collector reclaims the object. Java makes no guarantees about when garbage collection will occur or in what order objects will be collected. Therefore, Java can make no guarantees about when (or even whether) a finalizer will be invoked, in what order finalizers will be invoked, or what thread will execute finalizers. The Java interpreter can exit without garbage collecting all outstanding objects, so some finalizers may never be invoked. In this case, though, any outstanding resources are usually freed by the operating system. In Java 1.1, the Runtime method runFinalizersOnExit() can force the virtual machine to run finalizers before exiting. Unfortunately, however, this method can cause deadlock and is inherently unsafe; it has been deprecated as of Java 1.2. In Java 1.3, the Runtime method addShutdownHook() can safely execute arbitrary code before the Java interpreter exits. After a finalizer is invoked, objects are not freed right away. This is because a finalizer method can resurrect an object by storing the this pointer somewhere so that the object once again has references. Thus, after finalize() is called, the garbage collector must once again determine that the object is unreferenced before it can garbage-collect it. However, even if an object is resurrected, the finalizer method is never invoked more than once. Resurrecting an object is never a useful thing to do--just a strange quirk of object finalization. As of Java 1.2, the java.lang.ref.PhantomReference class can implement an alternative to finalization that does not allow resurrection.

Khoa CNTT H Nng Lm TP. HCM 01/2007

125/105

Arrays

An array is a structure that holds multiple values of the same type. The length of an array is established when the array is created. After creation, an array is a fixed-length structure.

An array element is one of the values within an array and is accessed by its position within the array. Arrays have certain performance characteristics, such as random access in constant time and linear lookup.
Khoa CNTT H Nng Lm TP. HCM 01/2007

126/105

Arrays

Declaring a Variable to Refer to an Array type[] array_name; int[] anArray = new int[10]; int[] anArray; float[] anArrayOfFloats; boolean[] anArrayOfBooleans; Object[] anArrayOfObjects; String[] anArrayOfStrings; Creating an Array anArray = new int[10]; new elementType[arraySize] Array Initializers boolean[] answers = { true, false, true};
Khoa CNTT H Nng Lm TP. HCM 01/2007

127/105

Arrays

Accessing an Array Element for (int i = 0; i < anArray.length; i++) { anArray[i] = i; System.out.print(anArray[i] + " "); } Getting the Size of an Array arrayname.length Arrays of Objects Arrays can hold reference types as well as primitive types.

public class ArrayOfStringsDemo { public static void main(String[] args) { String[] anArray = {"String One", "String Two","String Three"}; for (String s: anArray) { System.out.println(s.toLowerCase()); } }}
Khoa CNTT H Nng Lm TP. HCM 01/2007

128/105

Multidimensional Arrays

Khoa CNTT H Nng Lm TP. HCM 01/2007

129/105

Multidimensional Arrays

Khoa CNTT H Nng Lm TP. HCM 01/2007

130/105

A Example for Multidimension array


public class ArrayOfArraysDemo2 { public static void main(String[] args) { int[][] aMatrix = new int[4][]; //populate matrix for (int i = 0; i < aMatrix.length; i++) { aMatrix[i] = new int[5]; //create sub-array for (int j = 0; j < aMatrix[i].length; j++) { aMatrix[i][j] = i + j; } } //print matrix for (int i = 0; i < aMatrix.length; i++) { for (int j = 0; j < aMatrix[i].length; j++) { System.out.print(aMatrix[i][j] + " "); } System.out.println(); } }}
Khoa CNTT H Nng Lm TP. HCM 01/2007

131/105

Copying Arrays

Use System's arraycopy method to efficiently copy data from one array into another. The arraycopy method requires five arguments: public static void arraycopy(Object source,int srcIndex, Object dest,int destIndex, int length)

Khoa CNTT H Nng Lm TP. HCM 01/2007

132/105

Copying Arrays
public class ArrayCopyDemo { public static void main(String[] args) { char[] copyFrom = {'d','e','c','a','f','f', 'e','i','n','a','t','e','d' }; char[] copyTo = new char[7]; System.arraycopy(copyFrom, 2,copyTo, 0, 7); System.out.println(new String(copyTo)); } }

Khoa CNTT H Nng Lm TP. HCM 01/2007

133/105

Exercise
public class WhatHappens { public static void main(String[] args) { StringBuffer[] stringBuffers = new StringBuffer[10]; for (int i = 0; i < stringBuffers.length; i ++){ stringBuffers[i].append("String Buffer at index " + i);

Where is a bug?

Khoa CNTT H Nng Lm TP. HCM 01/2007

134/105

Characters and Strings

String A class for working with immutable (unchanging) data composed of multiple characters.

StringBuffer A class for storing and manipulating mutable data composed of multiple characters. This class is safe for use in a multi-threaded environment.
StringBuilder A faster, drop-in replacement for StringBuffer, designed for use by a single thread only.

Khoa CNTT H Nng Lm TP. HCM 01/2007

135/105

Characters
char ch = 'a'; char[] firstFiveLetters={'a','b','c','d','e' }; char ch = string.charAt(i); //Test whether a character is upper case. if (Character.isUpperCase(string.charAt(i)) { ... } //Convert a character to lower case. char ch = Character.toLowerCase(string.charAt(i)); //Determine if the character is a letter. if (Character.isLetter(string.charAt(i))) { ... }

Khoa CNTT H Nng Lm TP. HCM 01/2007

136/105

Character Class
Method boolean isLetter(char ch) boolean isDigit(char ch) Description Determines whether the specified char value is a letter or a digit, respectively. Determines whether the specified char value is white space according to the Java platform.

boolean isWhiteSpace(char ch)


boolean isUpperCase(char ch) boolean isLowerCase(char ch) char toUpperCase(char ch) char toLowerCase(char ch) toString(char ch)

Determines whether the specified char value is upper- or lowercase, respectively.


Returns the upper- or lowercase form of the specified char value. Returns a String object representing the specified character value.
137/105

Khoa CNTT H Nng Lm TP. HCM 01/2007

Creating Strings

String(byte[] bytes) Constructs a new String by decoding the specified array of bytes using the platform's default charset. String(byte[] bytes, String charsetName) Constructs a new String by decoding the specified array of bytes using the specified charset. String(char[] value) Allocates a new String so that it represents the sequence of characters currently contained in the character array argument. String(char[] value, int offset, int count) Allocates a new String that contains characters from a subarray of the character array argument.
Khoa CNTT H Nng Lm TP. HCM 01/2007

138/105

Creating Strings

String(int[] codePoints, int offset, int count) Allocates a new String that contains characters from a subarray of the Unicode code point array argument. String(String original) Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. String(StringBuffer buffer) Allocates a new string that contains the sequence of characters currently contained in the string buffer argument. String(StringBuilder builder) Allocates a new string that contains the sequence of characters currently contained in the string builder argument.
Khoa CNTT H Nng Lm TP. HCM 01/2007

139/105

Creating StringBuilder

StringBuilder() Constructs a string builder with no characters in it and an initial capacity of 16 characters. StringBuilder(CharSequence seq) Constructs a string builder that contains the same characters as the specified CharSequence. StringBuilder(int capacity) Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument. StringBuilder(String str) Constructs a string builder initialized to the contents of the specified string.
Khoa CNTT H Nng Lm TP. HCM 01/2007

140/105

Getting the Length


public class StringsDemo { public static void main(String[] args) { String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); StringBuilder dest = new StringBuilder(len); for (int i = (len - 1); i >= 0; i--) { dest.append(palindrome.charAt(i)); } System.out.format("%s%n", dest.toString()); } } In addition to length, the StringBuffer and StringBuilder classes have a method called capacity, which returns the amount of space allocated rather than the amount of space used.

Khoa CNTT H Nng Lm TP. HCM 01/2007

141/105

Getting Characters by Index

public char charAt(int index) Returns the char value in this sequence at the specified index. The first char value is at index 0. public String substring(int start) Returns a substring begins at the specified index and extends to the end of this sequence. public String substring(int start, int end) Returns a substring begins at the specified start and extends to the character at index end - 1.
Khoa CNTT H Nng Lm TP. HCM 01/2007

142/105

Getting Characters by Index


String anotherPalindrome = "Niagara. O roar again!"; char aChar = anotherPalindrome.charAt(9); String roar = anotherPalindrome.substring(11, 15);

Khoa CNTT H Nng Lm TP. HCM 01/2007

143/105

Searching for a Character or a Substring within a String (String class)


Method int indexOf(int) int lastIndexOf(int) int indexOf(int, int) int lastIndexOf(int, int) int indexOf(String) int lastIndexOf(String) int indexOf(String, int) int lastIndexOf(String, int) boolean contains(CharSequence) Description Returns the index of the first (last) occurrence of the specified character. Returns the index of the first (last) occurrence of the specified character, searching forward (backward) from the specified index. Returns the index of the first (last) occurrence of the specified string. Returns the index of the first (last) occurrence of the specified string, searching forward (backward) from the specified index. Returns true if the string contains the specified character sequence.

The StringBuffer and StringBuilder classes do not support the indexOf or the lastIndexOf methods. If you need to use these methods on either one of these objects, first convert to a string by using the toString method
Khoa CNTT H Nng Lm TP. HCM 01/2007

144/105

FilenameDemo
public class FilenameDemo { public static void main(String[] args) { final String FPATH = "/home/mem/index.html"; Filename myHomePage = new Filename(FPATH,'/', '.'); System.out.println("Extension = " + myHomePage.extension()); System.out.println("Filename = " + myHomePage.filename()); System.out.println("Path = " + myHomePage.path()); } Extension = html } Filename = index Path = /home/mem
Khoa CNTT H Nng Lm TP. HCM 01/2007

145/105

FileName
public class Filename { private String fullPath; private char pathSeparator, extensionSeparator; public Filename(String str, char sep, char ext) { fullPath = str; pathSeparator = sep; extensionSeparator = ext; } public String extension() { int dot = fullPath.lastIndexOf(extensionSeparator); return fullPath.substring(dot + 1); }
Khoa CNTT H Nng Lm TP. HCM 01/2007

146/105

FileName
public String filename() { int dot = fullPath.lastIndexOf(extensionSeparator); int sep = fullPath.lastIndexOf(pathSeparator); return fullPath.substring(sep + 1, dot); } public String path() { int sep = fullPath.lastIndexOf(pathSeparator); return fullPath.substring(0, sep); }

Khoa CNTT H Nng Lm TP. HCM 01/2007

147/105

Comparing Strings and Portions of Strings


Methods in the String Class for Comparing Strings Method Description Returns true if this string ends with or begins with the substring specified as an argument to the method. The integer argument, when present, indicates the offset within the original string at which to begin looking.

boolean endsWith(String) boolean startsWith(String) boolean startsWith(String, int)

Compares two strings lexicographically and returns an integer indicating whether this int compareTo(String) string is greater than (result is > 0), equal to int (result is = 0), or less than (result is < 0) the compareToIgnoreCase(Strin argument. The Object argument is converted g) to a string before the comparison takes place. The compareToIgnoreCase method ignores case; thus, "a" and "A" are considered equal.

Khoa CNTT H Nng Lm TP. HCM 01/2007

148/105

Comparing Strings and Portions of Strings


Methods in the String Class for Comparing Strings Method Description

Returns true if this string contains the same sequence of characters as the argument. boolean equals(Object) boolean equalsIgnoreCase(String) The Object argument is converted to a string before boolean the comparison takes place. contentEquals(CharSequence) The equalsIgnoreCase method ignores case; thus, "a" and "A" are considered equal.

Khoa CNTT H Nng Lm TP. HCM 01/2007

149/105

Modifying String Buffers and String Builders


Methods for Modifying a String Buffer

Method
StringBuffer append(boolean) StringBuffer append(char) StringBuffer append(char[]) StringBuffer append(char[], int, int) StringBuffer append(double) StringBuffer append(float) StringBuffer append(int) StringBuffer append(long) StringBuffer append(Object) StringBuffer append(String) StringBuffer delete(int, int) StringBuffer deleteCharAt(int)

Description

Appends the argument to this string buffer. The data is converted to a string before the append operation takes place.

Deletes the specified character(s) in this string buffer.


150/105

Khoa CNTT H Nng Lm TP. HCM 01/2007

Modifying String Buffers and String Builders


Methods for Modifying a String Buffer Method Description StringBuffer insert(int, boolean) StringBuffer insert(int, char) StringBuffer insert(int, char[]) StringBuffer insert(int, char[], int, int) StringBuffer insert(int, double) StringBuffer insert(int, float) StringBuffer insert(int, int) StringBuffer insert(int, long) StringBuffer insert(int, Object) StringBuffer insert(int, String) StringBuffer replace(int, int, String) void setCharAt(int, char) StringBuffer reverse()

Inserts the second argument into the string buffer. The first integer argument indicates the index before which the data is to be inserted. The data is converted to a string before the insert operation takes place.
Replaces the specified character(s) in this string buffer. Reverses the sequence of characters in this string buffer.

Khoa CNTT H Nng Lm TP. HCM 01/2007

151/105

Anda mungkin juga menyukai