part4-object oriented programming
TRANSCRIPT
-
8/2/2019 Part4-Object Oriented Programming
1/151
OBJECT ORIENTED PROGRAMMING
CLASSES AND OBJECT
SPECIAL JAVA SUBJECT
-
8/2/2019 Part4-Object Oriented Programming
2/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 2/105
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
-
8/2/2019 Part4-Object Oriented Programming
3/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 3/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
-
8/2/2019 Part4-Object Oriented Programming
4/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 4/105
Working with Classes
The class is the basis for object-oriented
programming
The data and the operations on the data areencapsulated in a class
A class is a template that contains the data variablesand the methods that operate on those datavariables following some logic
All the programming activity happens inside classes
-
8/2/2019 Part4-Object Oriented Programming
5/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 5/105
Working with Classes (cont.)
The data variables and the methods in a class arecalled class members
Variables, which hold the data (or point to it in case ofreference variables), are said to represent the state ofan object
The methods constitute class behavior
-
8/2/2019 Part4-Object Oriented Programming
6/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 6/105
The Elements of a class
-
8/2/2019 Part4-Object Oriented Programming
7/151Khoa CNTTH Nng Lm TP. HCM 01/2007 7/105
Defining Classes
A class is declared by using the keyword class
The general syntax for a class declaration is class { /**/ }
specifies the name of the class
specifies some characteristics of the class
(optional)
The modifiers group into the following twocategories:
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
-
8/2/2019 Part4-Object Oriented Programming
8/151Khoa CNTTH Nng Lm TP. HCM 01/2007 8/105
Declaring ClassesClass Declaration Elements
Element Function
@annotation (Optional) An annotation (sometimes called meta-data)
public (Optional) Class is publicly accessibleabstract (Optional) Class cannot be instantiatedfinal (Optional) Class cannot be subclassedclass NameOfClass Name of the class
(Optional) Comma-separated list of type variablesextends Super (Optional) Superclass of the classimplements Interfaces (Optional) Interfaces implemented by the class{
ClassBody}
Provides the class's functionality
-
8/2/2019 Part4-Object Oriented Programming
9/151Khoa CNTTH Nng Lm TP. HCM 01/2007 9/105
Declaring Member VariablesVariable Declaration Elements
Element Function
accessLevelpublic,protected,private
(Optional) Access level for the variable
static (Optional) Declares a class variablefinal (Optional) Indicates that the variable's value cannot
change
transient (Optional) Indicates that the variable is transient(should not be serialized)
volatile (Optional) Indicates that the variable is volatiletype name The type and name of the variable
-
8/2/2019 Part4-Object Oriented Programming
10/151Khoa CNTTH Nng Lm TP. HCM 01/2007 10/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
-
8/2/2019 Part4-Object Oriented Programming
11/151Khoa CNTTH Nng Lm TP. HCM 01/2007 11/105
Controlling Access to Members of a Class
Access Levels
Specifier Class Package Subclass World
private Y N N N
no specifier Y Y N N
protected Y Y Y N
public Y Y Y Y
-
8/2/2019 Part4-Object Oriented Programming
12/151Khoa CNTTH Nng Lm TP. HCM 01/2007 12/105
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 astatement with the new operator, it allocatesmemory for that instance. Subsequently, itexecutes the constructor to initialize the memory
-
8/2/2019 Part4-Object Oriented Programming
13/151Khoa CNTTH Nng Lm TP. HCM 01/2007 13/105
Writing and Invoking Constructors
ComputerLab csLab = new ComputerLab();
When the Java runtime system encounters thisstatement, it does the following, and in this order:
1. Allocates memory for an instance of classComputerLab
2. Initializes the instance variables of classComputerLab
3. Executes the constructor ComputerLab()
-
8/2/2019 Part4-Object Oriented Programming
14/151Khoa CNTTH Nng Lm TP. HCM 01/2007 14/105
Writing and Invoking Constructors
If you do not provide any constructor for a class you
write, the compiler provides the default constructorfor 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 withparameters
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
-
8/2/2019 Part4-Object Oriented Programming
15/151Khoa CNTTH Nng Lm TP. HCM 01/2007 15/105
Using Methods
Methods represent operations on data and also holdthe logic to determine those operations
Using methods offer two main advantages:
A method may be executed (called) repeatedly fromdifferent points in the program
Methods help make the program logically segmented,or modularized. A modular program is less error prone,and easier to maintain
-
8/2/2019 Part4-Object Oriented Programming
16/151Khoa CNTTH Nng Lm TP. HCM 01/2007 16/105
Defining a Method
Defining a method in a program is called methoddeclaration
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 themethod call
Return type: A method may optionally return a value as aresult of a method call. Special void return type
Access modifier: Each method has a default or specifiedaccess modifier
-
8/2/2019 Part4-Object Oriented Programming
17/151Khoa CNTTH Nng Lm TP. HCM 01/2007 17/105
Defining a Method (cont.)
Syntax
(){
// body of the method.
}
Example
public int square (int number) {
return number*number;}
Using
int myNumber = square(2);
Qualified method name:
.
-
8/2/2019 Part4-Object Oriented Programming
18/151Khoa CNTTH Nng Lm TP. HCM 01/2007 18/105
Defining a Method (cont.)
The method name and return type aremandatory in a method declaration
Methods and variables visibility:
In a normal case, methods and variables visibleonly within an instance of the class, and henceeach instance has its own copy of those methodsand variables
Those that are visible from all the instances ofthe class. Those are called static
-
8/2/2019 Part4-Object Oriented Programming
19/151Khoa CNTTH Nng Lm TP. HCM 01/2007 19/105
Defining Methods
Access level: public, protected, privateDefault is package private
-
8/2/2019 Part4-Object Oriented Programming
20/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 20/105
Defining MethodsElement Function
@annotation (Optional) An annotationaccessLevel (Optional) Access level for the methodstatic (Optional) Declares a class method (Optional) Comma-separated list of type variables.abstract (Optional) Indicates that the method must be
implemented in concrete subclasses.
final (Optional) Indicates that the method cannot beoverridden
synchronized (Optional) Guarantees exclusive access to this methodreturnType methodName The method's return type and name( paramList ) The list of arguments to the methodthrows exceptions (Optional) The exceptions thrown by the method
-
8/2/2019 Part4-Object Oriented Programming
21/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 21/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 anobject type.
2. Instantiation: The new keyword is a Java operatorthat creates the object. As discussed below, this is
also known as instantiating a class.3. Initialization: The new operator is followed by a call toa constructor. For example, Point(23, 94) is a call toPoint's only constructor. The constructor initializes thenew object.
-
8/2/2019 Part4-Object Oriented Programming
22/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 22/105
Declaring a Variable to Refer to an Object
typename This notifies the compiler that you will use name to
refer to data whose type is type. The Javaprogramming language divides variable types into twomain categories:primitivetypes, and referencetypes.
The declared type matches the class of the object:MyClassmyObject = new MyClass(); orMyClassmyObject;
The declared type is a parent class of the object'sclass:MyParentmyObject = new MyClass(); orMyParentmyObject
The declared type is an interface which the object'sclass implements:MyInterfacemyObject = new MyClass(); orMyInterfacemyObject
A variable in this state, which currently referencesnoobject, is said to hold a nullreference.
i i li i bj
-
8/2/2019 Part4-Object Oriented Programming
23/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 23/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);
i i li i Obj
-
8/2/2019 Part4-Object Oriented Programming
24/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 24/105
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 = newRectangle(originOne, 100, 200);
Initializing an Object
U i Obj
-
8/2/2019 Part4-Object Oriented Programming
25/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 25/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.variableNameSystem.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(); orobjectReference.methodName(argumentList);System.out.println("Area of rectOne: " +
rectOne.area());rectTwo.move(40, 72);
Th St ti M th d d V i bl
-
8/2/2019 Part4-Object Oriented Programming
26/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 26/105
The Static Methods and Variables
The static modifier may be applied to a variable, amethod, and a block of code
A static element of a class is visible to all the instancesof the class
If one instance makes a change to it, all the instancessee 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.
-
8/2/2019 Part4-Object Oriented Programming
27/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 27/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);
}
}
The Static Methods
-
8/2/2019 Part4-Object Oriented Programming
28/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 28/105
The Static Methods
A method declared static in a class cannot access thenon static variables and methods of the class
A static method can be called even before a singleinstance 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
-
8/2/2019 Part4-Object Oriented Programming
29/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 29/105
class MyClass {
String salute = "Hello";
public static void main(String[] args){
System.out.println("Salute: " + salute);
}
} Error: Cannot access a nonstatic variable from inside a
static method
U d di I d Cl M b
-
8/2/2019 Part4-Object Oriented Programming
30/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 30/105
Understanding Instance and Class Members
publicclass AClass {
publicintinstanceInteger = 0;
publicint instanceMethod() {returninstanceInteger;
}
publicstaticintclassInteger= 0;publicstaticint classMethod() {
returnclassInteger;
}
publicstaticvoid main(String[] args) {
AClass anInstance = new AClass();
AClass anotherInstance = new AClass();
U d t di I t d Cl M b
-
8/2/2019 Part4-Object Oriented Programming
31/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 31/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 froma class method//System.out.println("Instance method 1: " +
instanceMethod());
//System.out.println("Instance method 2: " +instanceInteger);
U d t di I t d Cl M b
-
8/2/2019 Part4-Object Oriented Programming
32/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 32/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 generallyrecommended.)
System.out.println("Class method from an Instance:" +
anInstance.classMethod());
//Instances share class variablesanInstance.classInteger= 9;
System.out.println("Class method from an Instance1:" +
anInstance.classMethod());System.out.println("Class method from an Instance2:" +anotherInstance.classMethod());
}}
I iti li i I t d Cl M b
-
8/2/2019 Part4-Object Oriented Programming
33/151
Khoa CNTTH 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;
static {try {errorStrings =
ResourceBundle.getBundle("ErrorStrings");
} catch (MissingResourceException e) {//error recovery code here}
}}
I iti li i I t d Cl M b
-
8/2/2019 Part4-Object Oriented Programming
34/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 34/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}}
}
Exercise
-
8/2/2019 Part4-Object Oriented Programming
35/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 35/105
Exercise
publicclass StringAnalyzer2 {private String origin;
private String delimiter;public StringAnalyzer2(String origin, String delimiter){
. . . . . .}
publicboolean hasMoreElement(){. . . . . .}public String getNextElement(){
. . . . . .
}}
Using Modifiers
-
8/2/2019 Part4-Object Oriented Programming
36/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 36/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 lesspublic.
Understanding Using Modifiers
-
8/2/2019 Part4-Object Oriented Programming
37/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 37/105
Understanding Using Modifiers
The final Modifier
The final modifier may be applied to a class, amethod, 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
Understanding Using Modifiers
-
8/2/2019 Part4-Object Oriented Programming
38/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 38/105
Understanding Using Modifiersclass Calculator {
final int dime = 10;
int count = 0;Calculator (int i) {count = i;
}}class RunCalculator {
public static void main(String[] args) {final Calculator calc = new Calculator(1);calc = new Calculator(2);
calc.count = 2;calc.dime = 11;System.out.println("dime: " + calc.dime);
}
}
Error: calc is final
Error: dime is final
OK: default access
Understanding Using Modifiers
-
8/2/2019 Part4-Object Oriented Programming
39/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 39/105
Understanding Using Modifiers
The native Modifier
In your applications, sometimes you will want touse 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. Thelibrary is loaded by making the following system
call:
System.loadLibrary("");
Understanding Using Modifiers
-
8/2/2019 Part4-Object Oriented Programming
40/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 40/105
Understanding Using Modifiers
class MyNativeExample {
native void myNativeMethod();
static {
System.loadLibrary("NativeMethodLib");
}
}
Understanding Using Modifiers
-
8/2/2019 Part4-Object Oriented Programming
41/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 41/105
Understanding Using Modifiers
The transient Modifier
an object may be stored in persistent storage (saydisk) outside of the JVM, for later use by the sameapplication, 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, orExternalizable
A variable declared transient is not stored The transient modifier can only be applied to
instance variables
Methods with a Variable Number of Parameters
-
8/2/2019 Part4-Object Oriented Programming
42/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 42/105
Methods with a Variable Number of Parameters
A new feature in J2SE 5.0 that lets you definemethods with a variable number of parameters
You can make several method calls with a variablenumber of arguments
These are also called variable-length argument
methods
Methods with a Variable Number of Parameters
-
8/2/2019 Part4-Object Oriented Programming
43/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 43/105
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 appearlast inside the parentheses of the method
The variable-length parameters list consists of atype followed by three dots and the name
Example
public void printStuff (String greet, int... values)
Methods with a Variable Number of Parameters
Methods with a Variable Number of Parameters
-
8/2/2019 Part4-Object Oriented Programming
44/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 44/105
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);
}
}
Methods with a Variable Number of Parameters
Methods with a Variable Number of Parameters
-
8/2/2019 Part4-Object Oriented Programming
45/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 45/105
public void printStuff (int... values, String greet)
public void printStuff (String greet, int... values, double dnum)
Error: variable-length parameter must
appear at the last
Method has at most one variable length parameter
Methods with a Variable Number of Parameters
Passing Arguments into Methods
-
8/2/2019 Part4-Object Oriented Programming
46/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 46/105
Passing Arguments into Methods
Assume you declare a variable in your method, andthen you pass that variable as an argument in a
method call
The question is: What kind of effect can the calledmethod have on the variable in your method?
There are two kind: pass-by-value
pass-by-reference
Passing a Primitive Variable
-
8/2/2019 Part4-Object Oriented Programming
47/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 47/105
Passing a Primitive Variable
When a primitive variable is passed as an argument ina method call, only the copy of the original variable is
passed
Any change to the passed variable in the calledmethod will not affect the variable in the calling
method It is called pass-by-value
Passing Primitive Variables
-
8/2/2019 Part4-Object Oriented Programming
48/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 48/105
Passing Primitive Variablespublicclass SwapNumber extends TestCase{
publicvoidswap(int a, int b){int c = a;
a = b;b = c;
}publicvoidtest(){
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);}
}
Passing Primitive Variables
-
8/2/2019 Part4-Object Oriented Programming
49/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 49/105
Passing Primitive Variablespublicclass SwapNumber extends TestCase{
publicvoidswap(Integer a1, Integer b1){Integer c = a1;
a1 = b1;b1 = c;
}publicvoidtest(){
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);
}}
Passing Object Reference Variables
-
8/2/2019 Part4-Object Oriented Programming
50/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 50/105
Passing Object Reference Variables When you pass an object variable into a method, you
must keep in mind that you're passing the objectreference, 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);
}}
Passing Object Reference Variables
-
8/2/2019 Part4-Object Oriented Programming
51/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 51/105
Passing Object Reference Variables
Before modify() d.height = 10
dim = 11After modify() d.height = 11
Passing Object Reference Variables
-
8/2/2019 Part4-Object Oriented Programming
52/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 52/105
Passing Object Reference Variables
publicclass PassingVar extends TestCase{publicvoid 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
Passing a Reference Variable
-
8/2/2019 Part4-Object Oriented Programming
53/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 53/105
Passing a Reference Variable
When you pass a reference variable in a method, youpass 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 objectare two different things, so note the following:
The original object can be changed in the calledmethod by using the passed reference to the object
However, if the passed reference itself is changedin the called method, for example, set to null orreassigned to another object, it has no effect on theoriginal reference variable in the calling method
JavaBeans Naming Standard for Methods
-
8/2/2019 Part4-Object Oriented Programming
54/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 54/105
JavaBeans Naming Standard for Methods
Methods can be used to set the values of the classvariables and to retrieve the values
Methods written for these specific purposes are calledget and set methods (also known as getter andsetter)
In special Java classes, called JavaBeans, the rules for
naming the methods (including get and set) areenforced as a standard
The private variables of a JavaBean called propertiescan only be accessed through its getter and setter
methods
JavaBeans Naming Standard for Methods
-
8/2/2019 Part4-Object Oriented Programming
55/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 55/105
The rules The naming convention for a property is: the first
letter of the first word in the name must belowercase and the first letter of any subsequentword in the name must be uppercase, e.g., myCow
The name of the getter method begins with getfollowed by the name of the property, with the first
letter of each word uppercasedA 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 eachword uppercasedA setter method must have the void return type
The getter and setter methods must be public
JavaBeans Naming Standard for Methods
JavaBeans Naming Standard for Methods
-
8/2/2019 Part4-Object Oriented Programming
56/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 56/105
public class ScoreBean {
private double meanScore;
// getter method for property meanScorepublic double getMeanScore() {
return meanScore;
}
// setter method to set the value of the property meanScorepublic void setMeanScore(double score) {
meanScore = score;
}
}
JavaBeans Naming Standard for Methods
Understanding Enums
-
8/2/2019 Part4-Object Oriented Programming
57/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 57/105
Understanding Enums
enum type defines a set of constants that are representedas unique identifiers
Like classes, all enum types are reference types, whichmeans that you can refer to an object of an enum typewith a reference
An enum type is declared with an enum declaration,which is a comma-separated list of enum constants thedeclaration may optionally include other components oftraditional classes, such as constructors, fields andmethods
Understanding Enums (cont.)
-
8/2/2019 Part4-Object Oriented Programming
58/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 58/105
Understanding Enums (cont.)
Each enum declaration declares an enum class withthe following restrictions:
enum types are implicitly final, because theydeclare constants that should not be modified
enum constants are implicitly static
Any attempt to create an object of an enum typewith operator new results in a compilation error
The enum constants can be used anywhere constantscan be used, such as in the case labels of switchstatements and to control enhanced for statements
-
8/2/2019 Part4-Object Oriented Programming
59/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 59/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 titleprivate 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; }
}
-
8/2/2019 Part4-Object Oriented Programming
60/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 60/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 Bookfor ( 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() );}
}
Inheritance
-
8/2/2019 Part4-Object Oriented Programming
61/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 61/105
Inheritance is a fundamental feature of object-oriented programming
It enables the programmer to write a class based onan 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 nonprivatemembers (methods and variables) of the superclass,and may define its own members as well
Inheritance (cont.)
-
8/2/2019 Part4-Object Oriented Programming
62/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 62/105
( )
Inheritance facilitates the reuse of code and helps toadapt programming to real-world situations
The keyword to derive a class from another class isextends
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
Inheritance (cont.)
-
8/2/2019 Part4-Object Oriented Programming
63/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 63/105
( )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;}
}
Abstract Classes
-
8/2/2019 Part4-Object Oriented Programming
64/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 64/105
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
Abstract Classes (cont.)
-
8/2/2019 Part4-Object Oriented Programming
65/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 65/105
( )
A abstract class may have one or more abstractmethods in any of the following ways:
The class may have one or more abstract methodsoriginally defined in it
The class may have inherited one or more abstractmethods 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 leastone method in the interface
if there is no abstract method in the class, it could stillbe declared abstract
Abstract Classes (cont.)
-
8/2/2019 Part4-Object Oriented Programming
66/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 66/105
( )
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.");
}
}
Abstract Classes (cont.)
-
8/2/2019 Part4-Object Oriented Programming
67/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 67/105
( )
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();
}
}
Writing and Using Interfaces
-
8/2/2019 Part4-Object Oriented Programming
68/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 68/105
g g
Java supports single inheritance. That means asubclass 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 moreinterfaces in addition to the superclass
An interface is a template that contains some methoddeclarations. The interface provides only declarations for the
methods, and no implementation
The class that inherits from an interface must providethe implementation for the methods declared in theinterface
What is an Interface
-
8/2/2019 Part4-Object Oriented Programming
69/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 69/105
An interfacedefines:
a protocol of behavior that can be implemented byany class anywhere in the class hierarchy;
a set of methods but does not implement them.
A class that implements the interface agrees toimplement all the methods defined in the interface,thereby agreeing to certain behavior.
Definition: An interfaceis a named collection of
method definitions, without implementations.
What is an Interface
-
8/2/2019 Part4-Object Oriented Programming
70/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 70/105
Because an interface is simply a list ofunimplemented, and therefore abstract, methods, you
might wonder how an interface differs from anabstract class. The differences are significant.
An interface cannot implement any methods,whereas an abstract class can.
A class can implement many interfaces but canhave only one superclass.
abstract class can define both abstract and non-abstract methods, an interface can have only
abstract methodsAn interface is not part of the class hierarchy.
Unrelated classes can implement the sameinterface.
Interface Characteristics
-
8/2/2019 Part4-Object Oriented Programming
71/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 71/105
All interface methods are implicitly public and abstract. Inother words, you do not need to actually type the public orabstract modifiers in the method declaration, but the method isstill always public and abstract.
Allvariables defined in an interface must be public, static,and finalin other words, interfaces can declare onlyconstants, not instance variables.
Interface methods must not be static. Because interface methods are abstract, they cannotbe
marked final, static, or native.
An interface can extendoneormore other interfaces.
An interfacecannotextendanything but another interface. An interfacecannotimplement another interface or class.
An interface must be declared with the keyword interface.
Interface types can be used polymorphically
Declaring Interface Constants
-
8/2/2019 Part4-Object Oriented Programming
72/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 72/105
interface Foo {
int BAR = 42;void go();
}
class Zap implements Foo {public void go() {
BAR = 27;}
}
//what is a bug?
Declaring Interface Constants
-
8/2/2019 Part4-Object Oriented Programming
73/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 73/105
Look for interface definitions that define constants, but withoutexplicitly 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
Steps in using a Interface
-
8/2/2019 Part4-Object Oriented Programming
74/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 74/105
define an INTERFACE that defines the methodheader for the desired method,
declare in each class that defines this method thatit IMPLEMENTS THE INTERFACE and
CAST the object that invokes the desired method to
be of the type for which the desired method isdefined.
Implementing an Interface
-
8/2/2019 Part4-Object Oriented Programming
75/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 75/105
class Foo { } //OKclass Bar implements Foo { } //No! Can't implement a classinterface Baz { } //OK
interface Fi { } // OKinterface Fee implements Baz { } //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 classinterface Boo extends Fi { } // OK. Interface can extend
// an interfaceclass Toon extends Foo, Button { } //No! Class can't extend
// multiple classesclass Zoom implements Fi, Fee { } // OK. class can implement
// multiple interfacesinterface Vroom extends Fi, Fee { } // OK. interface can extend
// multiple interfacesclass Yow extends Foo implements Fi { } // OK. Class can do
//both (extends must be 1st)
Writing and Using Interfaces (cont.)
-
8/2/2019 Part4-Object Oriented Programming
76/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 76/105
define an interface by the keyword interfaceinterface {
; ; ( ); ();
} // 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
Writing and Using Interfaces (cont.)
-
8/2/2019 Part4-Object Oriented Programming
77/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 77/105
interface ParentOne {
int pOne = 1;
void printParentOne();}
interface ParentTwo {
int pTwo = 2;void printParentTwo();
}
interface Child extends ParentOne, ParentTwo{
int child = 3;
void printChild();
}
Writing and Using Interfaces (cont.)
-
8/2/2019 Part4-Object Oriented Programming
78/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 78/105
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();
}}
Implement a Sorted list with Interface
-
8/2/2019 Part4-Object Oriented Programming
79/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 79/105
Consider the following problem
The bookstore managerwouldliketo have a list of
books ordered by the published year.
The runner would liketo have a list of entries orderedby the date
We need to developthe methodsortin the classAListand its derived classes.abstract public AList sort();
Implement a Sorted list with Interface
-
8/2/2019 Part4-Object Oriented Programming
80/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 80/105
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()))));
Implement a Sorted list with Interface
-
8/2/2019 Part4-Object Oriented Programming
81/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 81/105
We need to complete the method insert. // in the class MTList : insert the given book into this sorted list
of booksAList insert(Object b){
return new List(b, this);}
// to create from this list a new list sorted by the year publishedAList sort(){ return this;}
// in the class List : insert the given book into this sorted list ofbooksAList 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
publishedAList sort(){ return (this.rest.sort()).insert(this.fist); }
A Problem in the object comparing
-
8/2/2019 Part4-Object Oriented Programming
82/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 82/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?
The Interface Comparable
-
8/2/2019 Part4-Object Oriented Programming
83/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 83/105
interface Comparable{
// 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 thegiven object
// produce positive result if this is 'greater' thanthe given object
int compareTo(T obj);
}
Using the Comparable Interface
-
8/2/2019 Part4-Object Oriented Programming
84/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 84/105
public class Entryimplements IValuable,Comparable{
private Date date;private String comment;private double distance;private int duration;
// compare the date recorded in this entry with thegiven entrypublic int compareTo( Entry obj) {
return this.date.getDate() -
obj.date.getDate();}
}
Using the Comparable Interface
-
8/2/2019 Part4-Object Oriented Programming
85/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 85/105
public class Bookimplements IValuable,Comparable< Book>{
private Author author;private String title;private double cost;private int publishYear;
// compare the publication year of this book with thegiven bookpublicintcompareTo( Bookobj) {
returnthis.publishYear-obj.publishYear;
}}
Using the Comparable Interface
-
8/2/2019 Part4-Object Oriented Programming
86/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 86/105
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)));
}}
Objects that represent functions
-
8/2/2019 Part4-Object Oriented Programming
87/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 87/105
interface Comparator{int compare(Object obj1, Object obj2);
}
Object-Oriented Relationships
-
8/2/2019 Part4-Object Oriented Programming
88/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 88/105
In an application, the classes and class members arerelated 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 classesinside an application may have, and these kindscorrespond to the two properties of classes:
Inheritance (is-a relationship) Data abstraction (has-a relationship)
The is-a Relationship
-
8/2/2019 Part4-Object Oriented Programming
89/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 89/105
class Stereo {
}
class Boombox extends Stereo {
}
a boombox is a stereo
A rule of thumb to recognize an is-a relationship isthat every object of the subclass is also an object
of the superclass and not vice versa
The has-a Relationship
-
8/2/2019 Part4-Object Oriented Programming
90/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 90/105
The has-a relationship corresponds to an object-
oriented characteristic called encapsulation,which means the data and the methods arecombined into a structure called a class
class Stereo {}class Boombox extends Stereo {
CDPlayer cdPlayer = new CDPlayer();
}class CDPlayer {}
the boombox is-a stereoand it has-a CD player
Polymorphism
-
8/2/2019 Part4-Object Oriented Programming
91/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 91/105
The is-a relationship between a superclass and asubclass 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 superclassAnimal, because a cow is an animal
Animal a = new Animal();
a = new Cow(); // Now, a points to an object of Cow
Polymorphism (cont.)
-
8/2/2019 Part4-Object Oriented Programming
92/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 92/105
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 abuffalo for an animal
This is an example of polymorphism, which means
giving different meaning to the same thing
Polymorphism (cont.)l A i l {
-
8/2/2019 Part4-Object Oriented Programming
93/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 93/105
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!");
}
Polymorphism (cont.)
bli l T tP l {
-
8/2/2019 Part4-Object Oriented Programming
94/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 94/105
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();
}}
Polymorphism (cont.)
-
8/2/2019 Part4-Object Oriented Programming
95/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 95/105
The compiler only knows about the declared objectreference 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 onetype to another type is at the heart of polymorphism
Conversion of Data Types
-
8/2/2019 Part4-Object Oriented Programming
96/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 96/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 forconversion (type casting)
-
8/2/2019 Part4-Object Oriented Programming
97/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 97/105
Assignment Conversion
s = new ();
t = s; // Implicit conversion of to
Method Call Conversion
Arithmetic Conversion
Implicit Primitive Type Conversion
l l f l
-
8/2/2019 Part4-Object Oriented Programming
98/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 98/105
Two general rules for implicit primitive type conversionare the following:
There is no conversion between boolean and non-boolean types.
A non-boolean type can be converted into another non-boolean type only if the conversion is not narrowingthat is, the size of the target type is greater than orequal to the size of the source type.
Implicit Primitive Type Conversion
bli l C i T Wid {
-
8/2/2019 Part4-Object Oriented Programming
99/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 99/105
public class ConversionToWider{
public static void main(String[] args) {
int i = 15;
short s = 10;
i = s;
System.out.println("Value of i: " + i );
}
}
Error: Illegal conversion
Implicit Primitive Type Conversion
-
8/2/2019 Part4-Object Oriented Programming
100/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 100/105
Explicit Primitive Type Conversion
I i i ti i d t
-
8/2/2019 Part4-Object Oriented Programming
101/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 101/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.
Implicit Object Reference Types Conversion
th th ki d f bj t f t
-
8/2/2019 Part4-Object Oriented Programming
102/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 102/105
there are three kinds of object reference types:
A class
An interface
An array
Implicit Object Reference Types Conversion
A class t pe ma be con e ted to anothe class t pe if one of
-
8/2/2019 Part4-Object Oriented Programming
103/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 103/105
A class type may be converted to another class type if one ofthe following is true: The is a subclass of the . The implements the .
An interface type may be converted to one of the following: Another interface if the is a subinterface of
the .
The Objecttype if the is an object. An array may be converted to one of the following:
Another array if the following conditions are true: bothand are arrays of objectreference types, and the object reference type of
array elements is convertible to the objectreference types of array elements. The interface: Cloneable or Serializable. The class Object.
Explicit Object Reference Types Conversion
Two level of conversion
-
8/2/2019 Part4-Object Oriented Programming
104/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 104/105
Two level of conversion Compile time
Run TimeAt compile time, the following rules must be
obeyed: 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 beobject reference types and not primitive types. Also,
the object reference type of the source array mustbe convertible to the object reference type of thetarget array.
The casting between an interface and an objectthat is not final is always allowed.
Explicit Object Reference Types Conversion
If ti th il ti th th f ll i
-
8/2/2019 Part4-Object Oriented Programming
105/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 105/105
If a casting passes the compilation, then the followingrules are enforced at runtime:
If the target type is a class, then the class of theexpression being converted must be either thesame as the target type or its subclass.
If the target type is an interface, then the class ofthe expression being converted must implement thetarget type.
Explicit Object Reference Types Conversion
Auditorium a1 a2;
-
8/2/2019 Part4-Object Oriented Programming
106/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 106/105
Auditorium a1,a2;
ClassRoom c;
LectureHall lh;
a1 = new Auditorium();
c = a1;
a2 = (Auditorium) c;lh = (LectureHall) c;
OK: implicit conversion
OK: explicit conversion
Error: illegal conversion
Method Overriding and Overloading Method Overriding
-
8/2/2019 Part4-Object Oriented Programming
107/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 107/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 musthave the same return type. J2SE 5 allows a covariant returntype as well
The number of parameters and their types in the overridingmethod must be same as in the overridden method and thetypes must appear in the same order. However, the namesof the parameters may be different.
Overloading (cont.)Rules for method overriding (cont )
-
8/2/2019 Part4-Object Oriented Programming
108/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 108/105
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, aswell.
Each exception included in the throws clause of theoverriding method must be either one of the exceptionsin the throws clause of the overridden method or asubclass of it.
If the overridden method has a throws clause, the overridingmethod does not have to.
Overloading (cont.)A covariant return type of an overriding method is a
-
8/2/2019 Part4-Object Oriented Programming
109/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 109/105
A covariant return type of an overriding method is asubclass of the return type of the overridden method,
and is legal
public Number myMethod();public Double myMethod();
public int myMethod();
public double myMethod();
OK: Covariant returntype
Error: Difference return
type
Overloading (cont.) Method Overloading
-
8/2/2019 Part4-Object Oriented Programming
110/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 110/105
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
Constructor Overloading 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 programmerdefines no constructor in a class, the compiler adds the defaultconstructor with no arguments. If one or more constructors aredefined in the class, the compiler does not provide anyconstructor
Understanding Garbage Collection The process of freeing memory from the used objects is
-
8/2/2019 Part4-Object Oriented Programming
111/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 111/105
The process of freeing memory from the used objects iscalled 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 memorymanagement 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
Collection (cont.) There are two things that you can do in the code to
-
8/2/2019 Part4-Object Oriented Programming
112/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 112/105
There are two things that you can do in the code tohelp memory management:
Make an object eligible for garbage collection, becausea garbage collector will only free up memory from aneligible 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 aninstance of the Runtime class
Collection (cont.)class RuntimeTest {
-
8/2/2019 Part4-Object Oriented Programming
113/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 113/105
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());
}
}
Collection (cont.) A call to the garbage collector is no guarantee that the
-
8/2/2019 Part4-Object Oriented Programming
114/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 114/105
A call to the garbage collector is no guarantee that thememory will be free
The basic requirement for garbage collection is that youmust make your object eligible for garbage collection An object is considered eligible for garbage collection when there
is no reference pointing to it
You can remove the references to an object in two ways: Set the object reference variable pointing to the object to null Reassign a reference variable of an object to another object
finalize() Method What if you want an object to clean up its state before it is
-
8/2/2019 Part4-Object Oriented Programming
115/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 115/105
What if you want an object to clean up its state before it isdeleted? You can declare the finalize() method in the class
This method will be called by the garbage collector before deletingany 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 classinherited does not do anything
finalize() Method (cont.)
protected void finalize() {
-
8/2/2019 Part4-Object Oriented Programming
116/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 116/105
protected void finalize() {
super.finlaize();
// clean up code follows.
}
-
8/2/2019 Part4-Object Oriented Programming
117/151
OBJECT BASICS
Cleaning Up Unused Objects
The Java platform allows you to create as many
-
8/2/2019 Part4-Object Oriented Programming
118/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 118/105
The Java platform allows you to create as manyobjects as you want (limited, of course, by what your
system can handle), and you don't have to worryabout destroying them. The Java runtime environmentdeletes objects when it determines that they are nolonger being used. This process is called garbagecollection.
An object is eligible for garbage collection when thereare no more references to that object.
The Java runtime environment has a garbage collector
that periodically frees the memory used by objectsthat are no longer referenced. The garbage collectordoes its job automatically when it determines that thetime is right.
Cleaning Up: Nulling a Reference
The first way to remove a reference to an object
-
8/2/2019 Part4-Object Oriented Programming
119/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 119/105
The first way to remove a reference to an objectis 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
}}
Cleaning Up: Reassigning a Reference Variable
class GarbageTruck {
-
8/2/2019 Part4-Object Oriented Programming
120/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 120/105
class GarbageTruck {public static void main(String [] args) {
StringBuffer s1 = new StringBuffer("hello");StringBuffer s2 = new
StringBuffer("goodbye");System.out.println(s1);
// At this point the StringBuffer "hello" is not eligibles1 = s2;
// Redirects s1 to refer to the "goodbye" object// Now the StringBuffer "hello" is eligible for collection
}}
import java.util.Date;
Cleaning Up:Reassigning a Reference Variable
-
8/2/2019 Part4-Object Oriented Programming
121/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 121/105
p j ;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) ;}
}
Cleaning Up: Isolating a Reference
-
8/2/2019 Part4-Object Oriented Programming
122/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 122/105
Cleaning Up: Forcing Garbage Collection
import java.util.Date;
-
8/2/2019 Part4-Object Oriented Programming
123/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 123/105
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
-
8/2/2019 Part4-Object Oriented Programming
124/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 124/105
just before your object is deleted by the garbagecollector. 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, andyou'd like to close them before your object isdeleted. The problem is that, as you may have
gathered by now, you can't count on the garbagecollector to ever delete an object. So, any codethat 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 codeinto your finalize() method. In fact, we recommendthat in general you don't override finalize() at all
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
-
8/2/2019 Part4-Object Oriented Programming
125/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 125/105
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 neverbe invoked. In this case, though, any outstanding resources are usually freed by the operating system. InJava 1.1, the Runtime method runFinalizersOnExit() can force the virtual machine to run finalizers beforeexiting. 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 arbitrarycode before the Java interpreter exits.
After a finalizer is invoked, objects are not freed right away. This is because a finalizer method can resurrectan object by storing the this pointer somewhere so that the object once again has references. Thus, afterfinalize() is called, the garbage collector must once again determine that the object is unreferenced before itcan garbage-collect it. However, even if an object is resurrected, the finalizer method is never invoked morethan once. Resurrecting an object is never a useful thing to do--just a strange quirk of object finalization. Asof Java 1.2, the java.lang.ref.PhantomReference class can implement an alternative to finalization that doesnot allow resurrection.
Arrays An array is a structure that holds multiple values of
th t Th l th f i
-
8/2/2019 Part4-Object Oriented Programming
126/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 126/105
the same type. The length of an array isestablished when the array is created. After
creation, an array is a fixed-length structure.
An array element is one of the values within anarray and is accessed by its position within thearray. Arrays have certain performancecharacteristics, such as random access in constanttime and linear lookup.
Arrays Declaring a Variable to Refer to an Array
-
8/2/2019 Part4-Object Oriented Programming
127/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 127/105
type[] array_name;
int[] anArray = new int[10];int[] anArray;float[] anArrayOfFloats;boolean[] anArrayOfBooleans;Object[] anArrayOfObjects;
String[] anArrayOfStrings;
Creating an ArrayanArray = new int[10];
new elementType[arraySize]
Array Initializersboolean[] answers = { true, false, true};
Arrays Accessing an Array Element
f (i i 0 i l h i ) {
-
8/2/2019 Part4-Object Oriented Programming
128/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 128/105
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());
}}}
Multidimensional Arrays
-
8/2/2019 Part4-Object Oriented Programming
129/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 129/105
Multidimensional Arrays
-
8/2/2019 Part4-Object Oriented Programming
130/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 130/105
A Example for Multidimension arraypublic class ArrayOfArraysDemo2 {
public static void main(String[] args) {
-
8/2/2019 Part4-Object Oriented Programming
131/151
Khoa CNTTH Nng Lm TP. HCM 01/2007 131/105
public static void main(String[] args) {int[][] aMatrix = new int[4][];
//populate matrixfor (int i = 0; i < aMatrix.length; i++) {aMatrix[i] = new int[5]; //create sub-arrayfor (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();
}}}
Copying Arrays Use System's arraycopy method to efficiently
copy data from one array into another The
-
8/2/2019 Part4-Object Oriented Programming
132/151
Khoa CNTT H Nng Lm TP. HCM 01/2007 132/105
copy data from one array into another. Thearraycopy method requires five arguments:
public static void arraycopy(Object source,intsrcIndex, Object dest,int destIndex, intlength)
Copying Arrayspublic class ArrayCopyDemo {
bli t ti id i (St i [] ) {
-
8/2/2019 Part4-Object Oriented Programming
133/151
Khoa CNTT H Nng Lm TP. HCM 01/2007 133/105
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));
}}
Exercise
public class WhatHappens {
-
8/2/2019 Part4-Object Oriented Programming
134/151
Khoa CNTT H Nng Lm TP. HCM 01/2007 134/105
publicclass WhatHappens {publicstaticvoidmain(String[] args) {
StringBuffer[] stringBuffers = newStringBuffer[10];
for (int i = 0; i