Part4-Object Oriented Programming
Part4-Object Oriented Programming
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
3/105
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
4/105
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
5/105
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)
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
7/105
Declaring Classes
Element @annotation Class Declaration Elements Function (Optional) An annotation (sometimes called metadata)
public
abstract final class NameOfClass <TypeVariables> extends Super
implements Interfaces
{
ClassBody
8/105
accessLevel
transient
volatile
type name
9/105
methods
10/105
public
Y
11/105
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
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()
13/105
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
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
Syntax
Example public int square (int number) { return number*number;Qualified method name: } <objectname>.<methodna Using me> int myNumber = square(2);
17/105
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
18/105
Defining Methods
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
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.
21/105
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);
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) {
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);
25/105
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
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
28/105
class MyClass { String salute = "Hello"; public static void main(String[] args){ System.out.println("Salute: " + salute); } } Error: Cannot access a non
29/105
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
//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);
31/105
//...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
} } }
33/105
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(){ ...... } }
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.
36/105
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
37/105
38/105
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
40/105
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
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
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)
43/105
44/105
45/105
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
46/105
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
47/105
48/105
49/105
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
51/105
52/105
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
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
54/105
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
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
57/105
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
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() );
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
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
64/105
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
66/105
67/105
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.
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
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
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
73/105
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.
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
76/105
77/105
78/105
by the date
We need to develop the method sort in the class AList and its derived classes.
79/105
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
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?
82/105
83/105
84/105
85/105
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); }
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)
88/105
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
89/105
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
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
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(); } }
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
95/105
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)
96/105
Assignment Conversion <sourceType> s = new <sourceType>(); <targetType> t = s; // Implicit conversion of <sourceType> to <targetType> Method Call Conversion Arithmetic Conversion
97/105
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.
98/105
99/105
100/105
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.
101/105
102/105
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
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
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.
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 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.
107/105
Overloading (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.
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
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
110/105
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
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
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()); } }
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
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
114/105
finalize() Method
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
115/105
116/105
OBJECT BASICS
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
sb = null;
// Now the StringBuffer object is eligible for collection
119/105
class GarbageTruck { public static void main(String [] args) { StringBuffer s1 = new StringBuffer("hello"); StringBuffer s2 = new StringBuffer("goodbye"); System.out.println(s1); s1 = s2;
// Redirects s1 to refer to the "goodbye" object // Now the StringBuffer "hello" is eligible for collection
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
122/105
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
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.
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
129/105
Multidimensional Arrays
130/105
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)
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)); } }
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?
134/105
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.
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))) { ... }
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.
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
141/105
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
String anotherPalindrome = "Niagara. O roar again!"; char aChar = anotherPalindrome.charAt(9); String roar = anotherPalindrome.substring(11, 15);
143/105
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); }
147/105
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.
148/105
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.
149/105
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.
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.
151/105