0% found this document useful (0 votes)
19 views

Part 05 - Object Oriented Programming_2025

Chapter 3 of the document focuses on Object-Oriented Programming (OOP) concepts, including classes, objects, inheritance, polymorphism, and encapsulation. It explains how to define classes, create objects, use methods, and communicate between objects through messages. The chapter also emphasizes the importance of abstraction, encapsulation, and the relationships between objects in OOP.

Uploaded by

dominhphuoc68
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Part 05 - Object Oriented Programming_2025

Chapter 3 of the document focuses on Object-Oriented Programming (OOP) concepts, including classes, objects, inheritance, polymorphism, and encapsulation. It explains how to define classes, create objects, use methods, and communicate between objects through messages. The chapter also emphasizes the importance of abstraction, encapsulation, and the relationships between objects in OOP.

Uploaded by

dominhphuoc68
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 161

ADVANCED PROGRAMMING

Chapter 3: OBJECT ORIENTED


PROGRAMMING

CLASSES AND OBJECT


Outline
◼ Working with Classes and Objects
◼ Defining Classes

◼ Creating Objects

◼ Writing and Invoking Constructors

◼ Using Methods
◼ Defining a Method

◼ The Static Methods and Variables

◼ Methods with a Variable Number of Parameters

◼ JavaBeans Naming Standard for Methods

◼ Method Overriding and Overloading

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 2/48
Outline
◼ Inheritance
◼ Abstract Classes
◼ Writing and Using Interfaces
◼ Object-Oriented Relationships
◼ The is-a Relationship

◼ The has-a Relationship

◼ Polymorphism
◼ Conversion of Data Types
◼ Understanding Garbage Collection

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 3/48
What is Object-Oriented Programming?
Student
Class
- studentNo
- courseId
- name
- lecturer
- birthday
+ serLecturer()
+ enroll()
+ getStudents()

◼ OOP
◼ Map your problem in the real world
◼ Define “things” (objects) which can do something
◼ Create a “type” (class) for these objects so that you
don’t have to redo all the work in defining an objects
properties and behavior
◼ An OO program: “a bunch of objects telling each other
what to do by sending messages”. (Smalltalk)
Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 4/48
Example of problem in the real world
◼ Sở giao thông cần theo dõi việc đăng ký xe của người
dân. Dựa vào thông tin trị giá xe và dung tích xylanh
của xe, sở giao thông cũng tính mức thuế phải
đóng trước bạ khi mua xe như sau:
- Dưới 100cc, 1% trị giá xe.
- Từ 100 đến 200cc, 3% trị giá xe.
- Trên 200cc, 5% trị giá xe.
◼ Dùng lập trình hướng đối tượng để giải quyết bài toán
trên. Hàm main in ra menu lựa chọn các công việc:
1. Nhập thông tin và tạo các đối tượng xe1, xe2, xe3
2. Xuất bảng kê khai tiền thuế trước bạ của các xe.
3. Thoát

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 5/48
Results

Car

- triGia
- dungTich
- chuXe
- loaiXe
+ tinhThue()
+ toString()

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 6/48
Important OO concepts
◼ Abstraction
Objects & Class
Encapsulation

◼ Object state and behavior "P.I.E”


triangle
◼ Object identity
Abstraction
◼ Messages
Inheritance Polymorphism
◼ Encapsulation
◼ Information/implementation hiding

◼ Inheritance
◼ Polymorphism

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 7/48
Objects

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 8/48


State

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 9/48


Behavior
◼ What the object can do responding to a message.

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 10/48


Identity
◼ Something to distinguish between objects.

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 11/48


Object Example
◼ The car shown in the figure can be considered an object.
◼ It has an ID ("1"),

◼ state (its color, for instance, and other characteristics),

◼ an interface (a steering wheel and brakes, for example)

◼ and behavior (the way it responds when the steering wheel

is turned or the brakes are applied).

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 12/48


Classes
◼ A class
◼ Defines the characteristics and variables common to all
objects of that class
◼ Objects of the same class are similar with respect to:
◼ Interface
◼ Behavior (method)
◼ State (variable)
◼ Used to instantiate specific objects
◼ Provide the ability of reusability
Example: Car manufacturers use the same blueprint to
build many cars over and over

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 13/48
Class Example

◼ The car at the top of the


figure represents a class
◼ Notice that the ID and color
(and presumably other
state details) are not
known, but the interface
and behavior are.

◼ Below the "class" car are


two objects which provide
2

concrete installations of the


class 2

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 14/48
Working with Classes
◼ The class is the basis for object-oriented programming
◼ The data and the operations on the data are
encapsulated in a class
◼ A class is a template that contains the data variables
and the methods that operate on those data variables
following some logic
◼ All the programming activity happens inside classes

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 15/48


Working with Classes (cont.)
◼ The data variables and the methods in a class are
called class members
◼ Variables, which hold the data, are said to represent
the state of an object
◼ The methods constitute class’ behavior

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 16/48
Message and Object Communication
◼ Objects communicate via messages
◼ Messages in Java correspond to method calls (invocations)
◼ Three components comprise a message:
1. The object to whom the message is addressed (Your
Car)
2. The name of the method to perform (changeGears)
3. Any parameters needed by the method (lower gear)

sender target

setSomething()
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 17/48
Object Messaging Example
◼ By itself the car is incapable of
activity. The car is only useful
when it is interacted with by
another object
◼ Object 1 sends a message to
object 2 telling it to perform a
certain action +
◼ In other words, the driver
presses the car’s gas pedal to
accelerate.

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 18/48


Encapsulation
◼ Encapsulation: to group related things together, so as
to use one name to refer to the whole group.
– Functions/procedures encapsulate instructions

– Objects encapsulate data and related procedures

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 19/48


Information hiding
◼ Information hiding: encapsulate to hide internal
implementation details from outsiders
– Outsiders see only interfaces
– Programmers have the freedom in implementing
the details of a system.
– Hence, the ability to make changes to an object’s
implementation without affecting other parts of the
program
– public, private, and protected

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 20/48


Shape
Inheritance +draw()
+erase()
◼ “is-a” relations +move()
+setColor()
+getColor()
◼ The general classes can
be specialized to more specific classes
Circle Square Triangle

+flipVertical()
+flipHorizontal()

◼ Reuse of interfaces & implementation


◼ Mechanism to allow derived classes to possess
attributes and operations of base class
◼ We can design generic services before specializing
them

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 21/48


Example Inheritance in real world

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 22/48


Polymorphism
◼ Polymorphism:
– Ability to assume different forms or shapes.
– To exist in more than one form
◼ Object polymorphism:
– Objects of different derived classes can respond to

the same message, and they can respond


differently
– Example: on receiving message draw(), Rectangle

and Triangle objects perform different draw()


methods

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 23/48


Example Polymorphism in real world

Shape

+draw()
+erase()
+move()
+setColor()
+getColor()

Circle Square Triangle

+draw() +draw() +draw()


+move() +move() +move()

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 24/48


Java Class
Java Classes

public class Student {


Data private int age;
members private String name;
private Date birthDate;
Method public int getAge() {
return age;
}
}

Class Student with data members and an instance


method (accessor)

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 26/48


Classes
◼ Encapsulate attributes (fields) and behavior
(methods)
◼ Attributes and behavior are members of the class
◼ Members may belong to either of the following:
◼ The whole class
◼ Class variables and methods, indicated by the
keyword static
◼ Individual objects
◼ Instance variables and methods
◼ Classes can be
◼ Independent of each other
◼ Related by inheritance
◼ Related by type
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 27/48
Working with Objects
◼ Objects of pre-defined classes must be explicitly
created by new operator
– Allocate dynamic memory in heap memory

– A constructor will be called to initialize the newly

created object.
◼ Objects are manipulated via references
◼ Invoke object’s methods:
<object reference>.<method_name>(<arguments>)

public class StringTest {


public static void main(String args[]) {
String s1 = new String("Hello, ");
String s2 = s1.concat("world!");
System.out.println("Here is the greeting" + s2);
}
}
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 28/48
Defining a Class
◼ A class declaration specifies a type
– The identifier: specifies the name of the class
– Attributes, methods, and access control
◼ Attributes: public class BankAccount {
private String ownerName;
– object's instance variables private double balance;
public void getOwnerName() {
◼ Methods: return ownerName;
}
– tasks that the objects can do ...
◼ Access modifiers:
– public : Accessible anywhere by anyone
– protected : Accessible only to the class itself and to its
subclasses or other classes in the same “package”
– private : Only accessible within the current class
– default (no keyword): accessible within the current package
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 29/48
Implementing Classes
◼ Classes are grouped into packages
◼ A package contains a collection of logically-related
classes
◼ Source code files have the extension .java
◼ There is one public class per .java file
◼ A class is like a blueprint; we usually need to create
an object, or instance of the class

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 30 30/48


The Elements of a class

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 31/48
Class Declaration
◼ The optional extends clause
◼ Indicates the superclass
◼ The optional implements clause
◼ Lists the names of all the interfaces that the class
implements

public class BankAccount extends Account


implements Serializable, BankStuff {

// class body
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 32 32/48


Declaring Classes
Class Declaration Elements
Element Function

@annotation (Optional) An annotation (sometimes called meta-


data)
public (Optional) Class is publicly accessible
abstract (Optional) Class cannot be instantiated
final (Optional) Class cannot be subclassed
class NameOfClass Name of the class

<TypeVariables> (Optional) Comma-separated list of type variables

extends Super (Optional) Superclass of the class


implements Interfaces (Optional) Interfaces implemented by the class
{
ClassBody Provides the class's functionality
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 33/48


Class Modifiers
◼ Class modifiers affect how the class can be used.
◼ Examples: public, abstract, final
◼ public classes
◼ May be accessed by any java code that can access its
containing package
◼ Otherwise, it may be accessed only from within its
containing package
◼ abstract classes
◼ Can contain anything that a normal class can contain
◼ Variables, methods, constructors
◼ Provide common information for subclasses
◼ Cannot be instantiated
◼ A class is declared final if it permits no subclasses.
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 34/48
Constructors
◼ A method that sets up a new instance of a class
◼ The class body contains at least one constructor
◼ Use the new keyword with a constructor to create
instances of a class

Class instantiation

BankAccount account = new BankAccount();

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 35/48


Writing and Invoking Constructors
◼ If you do not provide any constructor for a class you
write, the compiler provides the default
constructor for that class
◼ If you write at least one constructor for the class,
the compiler does not provide a default 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
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 36/48
Writing and Invoking Constructors

ComputerLab csLab = new ComputerLab();


◼ When the Java runtime system encounters this

statement, it does the following, and in this order:


1. Allocates memory for an instance of class
ComputerLab
2. Initializes the instance variables of class
ComputerLab
3. Executes the constructor ComputerLab()

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 37/48
More about Constructors
◼ Used to create and initialize objects
◼ Always has the same name as the class it constructs
(case-sensitive)
◼ No return type
◼ Constructors return no value, but when used with
new, return a reference to the new object
public class BankAccount { Constructor
public BankAccount(String name)
setOwner(name); definition
}
}
Constructor use

BankAccount account = new BankAccount("Joe Smith");

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 38/48


Default Constructors
◼ Default constructor
◼ constructor with no arguments
◼ The Java platform provides a one only if you do not
explicitly define any constructor
◼ When defining a constructor, you should also provide
a default constructor
public class BankAccount {
public BankAccount() {
}

public BankAccount(String name)


setOwner(name);
}
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 39/48


Overloading Constructors

◼ Overloading
◼ When there are a number of constructors with
different parameters
◼ Constructors are commonly overloaded to allow
for different ways of initializing instances

BankAccount newAccount = new BankAccount();

BankAccount knownAccount =
new BankAccount(accountNumber);
BankAccount namedAccount =
new BankAccount("My Checking Account");

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 40/48


Constructor Example

◼ In a constructor, the keyword this is used to


refer to other constructors in the same class
...
public BankAccount(String name) {
super();
owner = name;
}

public BankAccount() {
this("TestName");
}

public BankAccount(String name, double initialBalance) {


this(name);
setBalance(initialBalance);
}
...

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 41/48


Constructor Chaining
◼ Constructor chaining
◼ When one constructor invokes another within the class
◼ Chained constructor statements are in the form:
this(argument list);
◼ The call is only allowed once per constructor
◼ It must be the first line of code
◼ Do this to share code among constructors

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 42/48


More on Constructor Chaining
• Superclass objects are built before the subclass
super(argument list)
– initializes superclass members

• The first line of your constructor can be:


super (argument list);
this (argument list);
• You cannot use both super() and this() in the same
constructor.
• The compiler supplies an implicit super() constructor
for all constructors.

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 43/48


Java Destructors?
◼ Java does not have the concept of a destructor for
objects that are no longer in use
◼ Deallocation (using the delete operator) is done
automatically by the JVM
◼ The garbage collector reclaims (gets) memory of
unreferenced objects
◼ The association between an object and an object
reference is severed by assigning another value to the
object reference, for example:
◼ objectReference = null;
◼ An object with no references is a candidate for
deallocation during garbage collection

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 44/48


Declaring Member Variables - Fields
◼ Fields
◼ Defined as part of the class definition
◼ Objects retain state in fields
◼ Each instance gets its own copy of the instance variables
◼ Fields can be initialized when declared
◼ Default values will be used if fields are not initialized

access modifier type

package com.megabank.models;

public class BankAccount { name


private String owner;
private double balance = 0.0;
}
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 45/48
Declaring Member Variables
Variable Declaration Elements
Element Function
accessLevel
public, protected, (Optional) Access level for the variable
private
static (Optional) Declares a class variable
(Optional) Indicates that the variable's value
final
cannot change
(Optional) Indicates that the variable is
transient
transient
(Optional) Indicates that the variable is
volatile
volatile
type name The type and name of the variable

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 46/48


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

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 47/48


Encapsulation
◼ Private state can only be accessed from methods
in the class
◼ Mark fields as private to protect (hide) the state
◼ Other objects must access private state through
public methods
package com.megabank.models;

public class BankAccount {


private String owner;
private double balance = 0.0;
}

public String getOwner() {


return owner;
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 48/48


Messages

◼ Use messages to invoke behavior in an object

BankAccount account = new BankAccount();


account.setOwner("Smith");
account.credit(1000.0);
account.debit(50.5);

account.debit(50.5)

parameters
receiver
message

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 49/48


Methods
◼ Methods define
◼ How an object responds to messages
◼ The behavior of the class
◼ All methods belong to a class

return method
access type name parameter list
modifier

public void debit (double amount) {


// Method body
// Java code that implements method behavior
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 50/48


Method Signatures
◼ A class can have many methods with the same name
◼ Each method must have a different signature
◼ The method signature consists of
◼ The method name
◼ Argument number and types

method name argument type

public void credit(double amount) {


...
}
signature
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 51/48
Method Parameters
◼ Arguments (parameters) are passed by
◼ Value for primitive types
◼ Object reference for reference types
◼ Primitive values cannot be modified when passed as
an argument

public void method1() {


int a = 0;
System.out.println(a); // outputs 0
method2(a);
System.out.println(a); // outputs 0
}
void method2(int a) {
a = a + 1;
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 52/48


Returning from Methods
◼ Methods return, at most, one value or one object
◼ If the return type is void, the return statement is
optional
◼ There may be several return statements
◼ Control goes back to the calling method upon executing
a return
public void debit(double amount) {
if (amount > getBalance()) return;
setBalance(getBalance() - amount);
}

public String getFullName() {


return getFirstName() + " " + getLastName();
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 53/48


Invoking Methods
◼ To call a method, use the dot (.) operator
– The same operator is used for both class and
instance methods
– If the call is to a method of the same class, the
dot operator is not necessary
BankAccount account = new BankAccount();
account.setOwner("Smith");
account.credit(1000.0);
System.out.println(account.getBalance());
...
BankAccount method

public void credit(double amount) {


setBalance(getBalance() + amount);
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 54/48


Method Overriding
◼ 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
1. You cannot override a method that has the final
modifier.
2. You cannot override a static method to make it non-
static.
3. The overriding method (subclass) and the
overridden method (superclass) must have the same
return type.

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 55/48
Method Overriding
◼ Rules for method overriding (cont.)
4. 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.
5. You cannot override a method to make it less
accessible.

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 56/48
Method Overriding
◼ Rules for method overriding (cont.)
6. If the overriding method has a throws clause in its
declaration (checked exceptions), 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.
7. If the overridden method has a throws clause, the
overriding method does not have to.

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 57/48
Method Overriding
class A {
public void methodA() throws RuntimeException
//…
}
}
class B extends A {
@override
public void methodA() throws ArithmeticException
//…
}
}
class C extends A {
@override
class A {
public void methodA() throws Exception {//Error
public void show(){
//…
// some code here }
} }
} class D extends A {
class B extends A @override
{ public void methodA() {
@override //…
public void show() { }
// some code here }
throw new ArrayIndexOutOfBoundsException();
}
} Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH
Lâm Nông Lâm01/2016
TP. HCM TP. HCM 58/48
Overriding
◼ Override a method when a new implementation in a
subclass is provided, instead of inheriting the
method with the same signature from the superclass
public class BankAccount {
private float balance;
public int getBalance() {
return balance;
}
}
public class InvestmentAccount extends BankAccount{
private float cashAmount
private float investmentAmount;
public int getBalance() {
return cashAmount + investmentAmount;
}
}
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 59/48
Questions of Method Overriding?
1 2

4
3

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 60/48


Overloading Methods
◼ Signatures permit the same name to be used for many
different methods
◼ Known as overloading
◼ Two or more methods in the same class may have the
same name but different parameters
◼ The println() method of
System.out.println() has 10 different parameter
declarations:
◼ boolean, char[], char, double, float,
int, long, Object, String and one with no
parameters
◼ You don't need to use different method names, for
example "printString", "printDouble", ...

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 61/48


Variable – Length Arguments
◼ The printf method takes any number of arguments
◼ You could use overloading to define a few versions of printf with
different argument lengths, but it takes any number of arguments
◼ To do this yourself, use "type ... variable"
◼ variable becomes an array of given type
◼ Only legal for final argument of method
◼ Examples
◼ public void printf(String format, Object ... args)

◼ public int max(int ... numbers)

◼ Can call max(1, 2, 3, 4, 5, 6) or max(someArrayOfInts)

◼ Use sparingly
◼ You usually know how many arguments are possible

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 62/48
Methods with Variable Argument Lists (var-args)
◼ When you are not sure how many arguments your
method is going to accept. To address this problem,
Java 1.5 introduced var-args.
◼ Var-args is a short name for variable arguments. In
Java, an argument of a method can accept arbitrary
number of values.
◼ The syntax for implementing var-args is as follows:
accessModifier type methodName(datatype… arg) {
// method body
}
accessModifier type methodName(datatype a, …, datatype… arg){
// method body
}

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 63/48
Varargs: Example 1
public class MathUtils {
public static int min(int ... numbers) {
int minimum = Integer.MAX_VALUE;
for (int number: numbers) {
if (number < minimum) {
minimum = number;
}
}
return minimum;
}

public static void main(String[] args) {


System.out.printf("Min of 2 nums: %d.%n", min(2,1));
System.out.printf("Min of 7 nums: %d.%n",
min(2,4,6,8,1,2,3));
}
}
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 64/48
Varargs: Example 2

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 65/48
main Method
◼ An application cannot run unless at least one class has a
main method
◼ The JVM loads a class and starts execution by calling the
main(String[] args) method
◼ public: the method can be called by any object

◼ static: no object need be created first

◼ void: nothing will be returned from this method

public static void main(String[] args) {


BankAccount account = new BankAccount();
account.setOwner(args[0]);
account.credit(Integer.parseInt(args[1]));
System.out.println(account.getBalance());
System.out.println(account.getOwner());
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 66/48


Defining a Method (cont.)
◼ The method name and return type are mandatory in a
method declaration
◼ Methods and variables visibility:
◼ In a normal case, methods and variables visible only
within an instance of the class, and hence each instance
has its own copy of those methods and variables
◼ Those that are visible from all the instances of the
class. Those are called static

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 67/48
Defining Methods

◼ Access level: public, protected, private


Default is package private
Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 68/48
Defining Methods
Element Function
@annotation (Optional) An annotation
accessLevel (Optional) Access level for the method
static (Optional) Declares a class method

<TypeVariables> (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 be
overridden
synchronized (Optional) Guarantees exclusive access to this
method
returnType methodName The method's return type and name
( paramList ) The list of arguments to the method
throws exceptions (Optional) The exceptions thrown by the method
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 69/48
Assignment - 1
◼ Viết chương trình xây dựng đối tượng CD gồm có các
thuộc tính sau:
o Mã CD là số nguyên, Tựa CD: chuỗi ký tự, Ca sỹ: chuỗi ký

tự, Số bài hát: số nguyên (>0), Giá thành : số thực (>0)


◼ Định nghĩa các phương thức get/set cho từng thuộc tính.

◼ Xây dựng lớp lưu danh sách các CD (dùng mảng).


1. Phương thức thêm 1 CD vào danh sách, thêm thành công
nếu không trùng mã CD và kích thước mảng còn cho phép.
2. Tính số lượng CD có trong danh sách.
3. Tình tổng giá thành của các CD.
4. Phương thức sắp xếp danh sách giảm dần theo giá thành.
5. Phương thức sắp xếp danh sách tăng dần theo tựa CD.
6. Phương thức xuất toàn bộ danh sách.
7. Viết lớp cho phần kiểm nghiệm.
Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 70/48
Creating Objects
◼ Point originOne = new Point(23, 94);
◼ Rectangle rectOne = new
Rectangle(originOne,100,200);
◼ Rectangle rectTwo = new Rectangle(50, 100);
Each statement has the following three parts:
1. Declaration: The code set in bold are all variable
declarations that associate a variable name with an
object type.
2. Instantiation: The new keyword is a Java operator
that creates the object. As discussed below, this is
also known as instantiating a class.
3. Initialization: The new operator is followed by a call to
a constructor. For example, Point(23, 94) is a call to
Point's only constructor. The constructor initializes the
new object.
Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 71/48
Declaring a Variable to Refer to an Object
type name ;
◼ This notifies the compiler that you will use name to
refer to data whose type is type. The Java
programming language divides variable types into two
main categories: primitive types, and reference types.
◼ The declared type matches the class of the object:
MyClass myObject = new MyClass(); or
MyClass myObject;
◼ The declared type is a parent class of the object's
class:
MyParent myObject = new MyClass(); or
MyParent myObject
◼ The declared type is an interface which the object's
class implements:
MyInterface myObject = new MyClass(); or
MyInterface myObject
◼ A variable in this state, which currently references no
object, is said to hold a null reference.

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 72/48
Initializing an Object
public class Point {
public int x = 0;
public int y = 0;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Point originOne = new Point(23, 94);

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 73/48
Initializing an Object
public class Rectangle {
public int width;
public int height;
public Point origin;
public Rectangle(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}
}

Rectangle rectOne = new


Rectangle(originOne, 100, 200);
Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 74/48
Using Objects
◼ You can use an object in one of two ways:
◼ Directly manipulate or inspect its variables
◼ Call its methods
◼ Referencing an Object's Variables
The following is known as a qualified name:
objectReference.variableName
System.out.println("Width of rectOne: " +
rectOne.width);
System.out.println("Height of rectOne: " +
rectOne.height);
int height = new Rectangle().height;
◼ Calling an Object's Methods
objectReference.methodName(); or
objectReference.methodName(argumentList);
System.out.println("Area of rectOne: " +
rectOne.area());
rectTwo.move(40, 72);

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 75/48
The Static Methods and Variables
◼ The static modifier may be applied to a variable, a
method, and a block of code
◼ A static element of a class is visible to all the instances
of the class
◼ If one instance makes a change to it, all the instances
see that change
◼ A static variable is initialized when a class is loaded,
◼ An instance variable is initialized when an instance

of the class is created


◼ A static method also belongs to the class, and not to a
specific instance of the class
◼ Therefore, a static method can only access the

static members of the class.


Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 76/48
Static Members
◼ Static fields and methods belong to the class
◼ Changing a value in one object of that class changes
the value for all the objects
◼ Static methods and fields can be accessed
without instantiating the class
◼ Static methods and fields are declared using the
static keyword
public class MyDate {
public static long getMillisSinceEpoch(){

}
}
...
long millis = MyDate.getMillisSinceEpoch();
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 77/48
The Static Methods
◼ A method declared static in a class cannot access the
non static variables and methods of the class
◼ A static method can be called even before a single
instance of the class exists
◼ Static method main(), which is the entry point for

the application execution


◼ It is executed without instantiating the class in

which it exists

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 78/48
Example
class MyClass {
String salute = "Hello";
public static void main(String[] args){
System.out.println("Salute: " + salute);
}
}
Error: Cannot access a non
static variable from inside a
static method

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 79/48
Assignment - 2
◼ Hãy định nghĩa lớp “kiến” (Ant):
◼ Mỗi một đối tượng tạo ra từ lớp Ant này là 1 con kiến
◼ Tất cả các con kiến tạo ra từ cùng lớp Ant này tạo ra
một đàn kiến
◼ giả sử kiến không chết
◼ Hãy thiết kế lớp Ant sao cho khi hỏi 1 con kiến bất kỳ
trong đàn thì nó cũng cho ta biết tổng số con kiến có
trong đàn

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 80/48


Using Modifiers

◼ You cannot specify any modifier for the variables


inside a method
◼ You cannot specify the protected modifier for a
top-level class (là một lớp được khai báo trực tiếp
bên ngoài, không nằm trong lớp khác.)
◼ A method cannot be overridden to be less public.

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 81/48
Final Modifiers
◼ The final Modifier
◼ The final modifier may be applied to a class, a

method, or a variable. It means, in general, that


the element is final
◼ If the element declared final is a variable, that

means the value of the variable is constant, and


cannot be changed
◼ If a class is declared final, it means the class

cannot be extended
◼ If a final method cannot be overridden

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 82/48
Final Modifiers
class Calculator {
final int dime = 10;
int count = 0;
Calculator (int i) {
count = i;
}
}
class RunCalculator { Error: calc is final
public static void main(String[] args) {
final Calculator calc = new Calculator(1);
calc = new Calculator(2);
calc.count = 2;
calc.dime = 11; OK: default access
System.out.println("dime: " + calc.dime);
Error: dime is final
}
}

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 83/48
Final Members
◼ A final field is a field which cannot be modified
◼ This is the java version of a constant
◼ Constants associated with a class are typically
declared as static final fields for easy access
◼ A common convention is to use only uppercase letters
in their names

public class MyDate {


public static final long
SECONDS_PER_YEAR = 31536000;
...
}
...
long years = MyDate.getMillisSinceEpoch()/
(1000 * MyDate.SECONDS_PER_YEAR);
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 84/48
Passing Arguments into Methods
◼ Assume you declare a variable in your method, and
then you pass that variable as an argument in a
method call
◼ The question is: What kind of effect can the called
method have on the variable in your method?
◼ There are two kind:
◼ pass-by-value

◼ pass-by-reference

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 85/48
Passing a Primitive Variable
◼ When a primitive variable is passed as an argument in
a method call, only the copy of the original variable is
passed
◼ Any change to the passed variable in the called
method will not affect the variable in the calling
method
◼ It is called pass-by-value

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 86/48
Passing Primitive Variables
public class SwapNumber extends TestCase{
public void swap(int a, int b){
int c = a;
a = b;
b = c;
}
public void test(){
int a = 1, b = 2;
System.out.println("Before swap a: "+
a + " , b: "+b);
swap(a,b);
System.out.println("After swap a: "+
a + " , b: "+b);
}
}

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 87/48
Passing Primitive Variables
public class SwapNumber extends TestCase{
public void swap(Integer a1, Integer b1){
Integer c = a1;
a1 = b1;
b1 = c;
}
public void test(){
Integer a = new Integer (1),
b = new Integer (2);
System.out.println("Before swap a: "+
a + " , b: "+b);
swap(a,b);
System.out.println("After swap a: "+
a + " , b: "+b);
}
}

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 88/48
Passing Object Reference Variables
◼ When you pass an object variable into a method, you
must keep in mind that you're passing the object
reference, and not the actual object itself.
import java.awt.Dimension;
class ReferenceTest {
public static void main (String [] args) {
Dimension d = new Dimension(5,10);
ReferenceTest rt = new ReferenceTest();
System.out.println("Before modify() d.height = "+
d.height);
rt.modify(d);
System.out.println("After modify() d.height = "+ d.height);
}
void modify(Dimension dim) {
dim.height = dim.height + 1;
System.out.println("dim = " + dim.height);
}
}

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 89/48
Passing Object Reference Variables

Before modify() d.height = 10


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

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 90/48
Passing Object Reference Variables

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 91/48
Passing a Reference Variable
◼ When you pass a reference variable in a method, you pass
a copy of it and not the original reference variable
◼ The called method can change the object properties by
using the passed reference
◼ Changing the object and the reference to the object are
two different things, so note the following:
◼ The original object can be changed in the called
method by using the passed reference to the
object
◼ However, if the passed reference itself is changed in
the called method, for example, set to null or
reassigned to another object, it has no effect on the
original reference variable in the calling method

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 92/48
Assignment-3
◼ Viết lớp HangThucPham mô tả một hàng hóa là hàng thực
phẩm trong kho của một siêu thị, có các thuộc tính: mã hàng
(không cho phép sửa, không được để rỗng), tên hàng (không
được để rỗng), đơn giá (>0), ngày sản xuất và ngày hết hạn
(ngày không được để rỗng, ngày hết hạn phải sau ngày sản
xuất). Ràng buộc chặt chẽ các ràng buộc trên các trường dữ
liệu. Nếu dữ liệu không hợp lệ thì gán giá trị mặc định cho
phép tương ứng của trường đó.
◼ Tạo 1 constructor có đầy đủ tham số, 1 constructor có tham số
là mã hàng. Viết các phương thức setters/getters.
◼ Viết phương thức kiểm tra một hàng thực phẩm đã hết hạn
chưa?
◼ Phương thức toString, trả về chuỗi chứa thông tin của hàng
thực phẩm. Trong đó: Định dạng đơn giá có phân cách hàng
nghìn. Định dạng kiểu ngày là dd/MM/yyyy.
◼ Viết lớp cho phần kiểm nghiệm
Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 93/48
Chapter 4: Inheritance &
Polymorphism
Inheritance
◼ Based on "is-a" relationship Person

◼ Subclass: more specialized,


superclass: more general Student Employee

◼ Subclass is derived
or inherits from superclass FullTimeStudent PartTimeStudent Manager

◼ In essence:
◼ Objects in the same class have the same set of
attributes (different values) and operations
◼ Objects of subclass have all members of superclass
plus some more
◼ Objects of a subclass can also be treated as objects of
its superclass
Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 95/48
Inheritance
◼ An Employee “is a” Person,
◼ apart from its own members,
salary and getSalary(), Person

it also has name, birthday, -name


-birthday
getName() without having +getName()
to declare them +getBirthday()

◼ Employee is the subclass (derived) of


Person
Employee
◼ Person is the superclass (base) of -salary
Employee +getSalary()

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 96/48
Inheritance
◼ Inheritance tree can Person

have many levels -name: String


-birthday: Date
◼ A Manager object inherits +getName(): String

what an Employee has, +getBirthday(): Date

including what a Person


has.
Student Employee

-id: String -salary: double

+...() +getSalary(): double

Manager

-assistant: Employee

+setAssistant(emp: Employee)

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 97/48
Defined inheritance in Java

◼ Using extends clause

public class Person {


private String name;
private Date birthday;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
} class Employee extends Person {
} private double salary;
public void setSalary(double salary) {
this.salary = salary;
}
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 98/48


New attributes/operations

//application code
...
Employee e = new Employee();
e.setName("John"); call to Person’s setName() method
System.out.print(e.getName());
e.setSalary(3.0);

call to Employee’s setSalary() method

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 99/48


Override Method - subclass
◼ A subclass can redefine methods inherited from its
superclass.
◼ To specialize these methods to suit the new problem
◼ Objects of the subclass will work with the new version
of the methods
◼ Dynamic binding (runtime)
◼ Superclass’s methods of the same name can be
reused by using the keyword super

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 100/48


Overriding

public class BankAccount {


private float balance;
public int getBalance() {
return balance;
}
}

public class InvestmentAccount extends BankAccount {


private float cashAmount
private float investmentAmount;
public int getBalance() {
return cashAmount + investmentAmount;
}
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 101/48


More Example
◼ Subclass's version calls superclass's version then
does something extra

Call method of the superclass


public class Person { from within the subclass.
protected String name; Keyword super is the
protected Date birthday; reference to the superclass
public void display() {
System.out.print (name + "," + birthday);
}
... public class Employee extends Person {
} ...
public void display() {
super.display();
System.out.print ("," + salary);
}
}

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 102/48
Method overriding - Rules
◼ New and old version must have the same prototype:
◼ Same return type
◼ Same argument type
◼ Private methods cannot be overridden
◼ Private members are hidden from subclass

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 103/48
Access control levels

Modifier Accessible within


Same Same Subclasses Universe
class package

private yes
package yes yes
(default)
protected yes yes yes
public yes yes yes yes

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 104/48
protected access level
◼ protected members of a superclass are directly
accessible from inside its subclasses.

public class Person { Subclass can directly access


protected String name; superclass‘s protected members
protected Date birthday;
...
} public class Employee extends Person {
...
public String toString() {
String s;
s = name + "," + birthday; //no error.
s += "," + salary;
return s;
}
}

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 105/48
In the same package

◼ Default access level is “package”, which means those


with “package” access level can be accessed directly
from within the same package
package people;
public class Person {
package people; String name;
public class Employee extends Person { Date birthday;
... ...
public String toString() {
String s;
s = name + "," + birthday; //no error.
s += "," + salary;
return s;
}
}

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 106/48
In different packages
◼ Members with “package” access level cannot be
accessed directly by subclasses from outside the
package
package people;
public class Person {
package other;
String name;
Date birthday;
import people.Person;
...
public class Employee extends Person {
...
public String toString() {
String s;
s = name + "," + birthday; // error.
s += "," + salary;
return s;
}
}

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 107/48
In different packages
◼ Members with “protected” access level can be
accessed directly by subclasses from outside the
package
package people;
public class Person {
package other;
protected String name;
protected Date birthday;
import people.Person;
...
public class Employee extends Person {
...
public String toString() {
String s;
s = name + "," + birthday; // OK
s += "," + salary;
return s;
}
}

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 108/48
Constructor of subclass
◼ Subclass inherits all attributes/ methods of superclass
◼ Subclass must initialize inherited members
◼ But, constructors are NOT inherited
◼ syntactically, they have different names
◼ Two ways to call constructors of the base class
1. Implicit use default constructors
2. Explicit calls to constructors of the base class

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 109/48
Call default constructor

class Shape { The compiler supplies an


protected int x, y; implicit super() constructor
public Shape() {}
for all constructors.
public Shape(int x, int y) {
this.x = x;
this.y = y;
} Default constructor Shape() is called
}
class Circle extends Shape {
protected int radius;
public Circle() {}
}

// client code Cannot found Circle(int, int).


Shape p = new Shape(10, 10); Shape(int, int) is not inherited
Circle c1 = new Circle();
Circle c2 = new Circle(10, 10); // error

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 110/48


Calling constructors of base class
◼ The initializing superclass' attributes should be carried
out by baseclass' constructors
◼ Superclass' constructors can be called using reference
super
◼ Superclass' constructors must run first
super(argument list);
◼ If superclass has no default constructor then its
constructor must be called explicitly

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 111/48
Calling constructors of baseclass

class Shape {
protected int x, y;
public Shape(int x, int y) {
this.x = x;
this.y = y;
}
} Explicit calls to
Shape(int, int)
class Circle extends Shape {
protected int radius;
public Circle(int x, int y, int radius) {
super(x, y);
this.radius = radius;
}
} // client code
Shape p = new Shape(10, 10);
Circle c2 = new Circle(10, 10, 5); // OK

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 112/48


Calling constructors of baseclass

class Shape {
protected int x, y;
public Shape(int x, int y) {
this.x = x;
this.y = y;
}
} Error! Default constructor
Shape() is not found
class Circle extends Shape {
protected int radius;
public Circle(int x, int y, int radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 113/48


toString() method

◼ Inherits from Object class

class Shape {
protected int x, y;
public String toString() {
return "<" + x + "," + y + ">";
}
} Overriding Object's toString()
New versions are used in
class Circle extends Point {
protected int radius; System.out.println()
public String toString() {
return super.toString() + "," + radius;
}
} // client code
Circle c = new Circle();
System.out.println(c);

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 114/48
Reusing Classes
◼ Object classes with similar or related attributes
and behavior
◼ Person, Student, Manager,…
◼ Code reuse
◼ Composition – “has-a” relationship
◼ the new class is composed of objects of existing

classes.
◼ reuse the functionality of the existing class

◼ Inheritance – “is-a” relationship


◼ create a new class as a type of an existing class

◼ new class absorbs the existing class's members and

extends them with new or modified capabilities


Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 115/48
Reusing classes - composition

◼ A class can have references to objects of other


classes as members.
◼ This is called composition and is sometimes
referred to as a has-a relationship.

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 116/48


Example

public class Student {


private String name;
private Date birthday;

public Student(String name, public class Date {


Date birthday) { private int day;
this.name = name; private int month;
this.birthday = birthday; private int year;
}
} public Date(int day,
int month,
int year) {
this.day = day;
this.month = month;
this.year = year;
}
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 117/48


Person
What is polymorphism? -name: String
-birthday: Date
+getName(): String
+getBirthday(): Date
◼ Polymorphism: exist in many forms
Student Employee
◼ Polymorphism in programming -id: String -salary: double
+...() +getSalary(): double
◼ Function polymorphism: same name, different
arguments Manager
-assistant: Employee

◼ Object polymorphism: +setAssistant(emp: Empl

◼ An object can be treated in different ways


◼ A Manager object can be seen as an Employee object as
well
◼ Different objects interpret (implement) the same
message differently
◼ How do kangaroos and frogs "jump"?

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 118/48
class Animal {
...
public void makeASound() {
System.out.print ("Uh oh!");
}
}
class Cat extends Animal {
...
public void makeASound() {
System.out.print ("Meow...");
}
} Polymorphism:
class Cow extends Animal { The same message "makeASound"
... is interpreted differently
public void makeASound() {
System.out.print ("Moo..."); Meow... Moo...
}
} Animal myPets[] = new Animal[2];
myPets[0] = new Cat("tom");
myPets[1] = new Cow("mini");
for ( int i = 0; i < myPets.length; i++ ) {
myPets[i].makeASound();
}
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 119/48
class Animal {
...
public void makeASound() {
System.out.print ("Uh oh!");
} Polymorphism: The same message
public void introduce() { "makeASound" is interpreted differently
makeASound();
System.out.println(" I'm " + name);
}
}
class Cat extends Animal {
...
public void makeASound() {
Animal pet1 = new Cat("Tom Cat");
System.out.print("Meow...");
Animal pet2 = new Cow("Mini Cow");
}
pet1.introduce();
}
pet2.introduce();
class Cow extends Animal {
...
public void makeASound() { Meow... I'm Tom Cat
System.out.print("Moo..."); Moo... I'm Mini Cow
}
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 120/48


Dynamic & static binding
◼ Method binding: connect a method call to a method
body
◼ Static/early binding: performed by compiler/linker
before the program is run.
◼ The only option of procedural languages.
◼ Dynamic/late binding: performed during run-time
◼ Java uses late binding, except for static, final, and
private methods.

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 121/48
Chapter 5: Abstract class and
interface
Abstract class
◼ Sometimes we don't Shape

want objects of a base +area()


+perimeter()
class to be created
Circle Square Triangle

◼ Examples: +area()
+perimeter()
+area()
+perimeter()
+area()
+perimeter()

◼ Animal, Cat, Cow, Dog,…


◼ An Animal object makes no sense
◼ What sort of sound does it make?
◼ Shape, Point, Rectangle, Triangle, Circle
◼ What does a generic Shape look like?
◼ How to draw it?
◼ Solution: make it an abstract base class
Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 123/48
Abstract Classes
◼ Abstract classes cannot be instantiated – they are
intended to be a superclass for other classes
◼ abstract methods have no implementation
◼ If a class has one or more abstract methods, it is
abstract, and must be declared so
◼ Concrete classes have full implementations and can be
instantiated

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 124/48


Example

Shape CartesianPoint
# CartesianPoint location - int x
- int y
+ double area()

Dot Square Circle


- int size - int radius
+ double area()
+ double area() + double area()

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 125 125/48


public class CartesianPoint {
private int x;
private int y;
public CartesianPoint(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public abstract class Shape {
}
protected CartesianPoint location;
public Shape(CartesianPoint location) {
this.location = location;
}
public abstract double area();
public abstract double perimeter();
public abstract void draw();
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 126/48


public class Circle extends Shape {
private int radius;

public Circle(CartesianPoint location, int radius) {


super(location);
this.radius = radius;
}

public double area() {


return Math.PI * radius * radius;
}

public double perimeter() {


return 2 * Math.PI * this.radius;
}

public void draw() {


System.out.println("Draw circle at ("+ x + ","
+ y + ")");
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 127/48


BÀI TẬP
◼ Quản lý các đối tượng trong một học viện:
◼ Nhân viên quản lý (mã nv, tên nv, trình độ, chuyên
môn, lương cơ bản, phụ cấp chức vụ)
Lương = lương cơ bản + phụ cấp chức vụ
◼ Nhân viên nghiên cứu (mã nv, tên nv, trình độ, lương
cơ bản, phụ cấp độc hại)
Lương = lương cơ bản + phụ cấp đọc hại
◼ Nhân viên phục vụ: (mã nv, tên nv, trình độ, lương cơ
bản)
Lương = lương cơ bản

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 128/48
BÀI TẬP

◼ Xây dựng lớp HocVien (học viện) để quản lý danh


sách nhân viên của học viện, và thực hiện các yêu cầu
sau:
◼ In ra danh sách các nhân viên
◼ Tính tổng lương của tất cả các nhân viên có trong học viện
◼ Tìm nhân viên có mức lương thấp nhất, và in ra thông tin
của nhân viên này.

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 129/48
Java interfaces
◼ Java does not support multiple inheritance
◼ This is often problematic
◼ What if we want an object to be multiple things?
◼ Interfaces
◼ A special type of class which
◼ Defines a set of method prototypes
◼ Does not provide the implementation for the prototypes
◼ Can also define final constants

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 130/48
Interfaces
◼ Declared types in Java are either classes or interfaces
◼ An interface defines a protocol (a set of methods)
◼ If a class implements a given interface, then that class
implements that protocol.”

public interface File {


public void open(String name);
public void close();
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 131/48


Protocols
◼ An interface can impose a common protocol on a
group of classes that are not related by inheritance

<<interface>>
Comparable
+compareTo()

Date Integer String

+compareTo() +compareTo() +compareTo()

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 132/48


Declaring an Interface
◼ Interface definition has two components
– Interface declaration
– Interface body

Interface
Declaration public interface StockWatcher {
final string sunTicker = "SUNW"; Constant
Interface final string oracleTicker = "ORCL"; Declarations
Body final string ciscoTicker = "CSCO";
void valueChanged(String tickerSymbol, Method
double newvalue); Declaration
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 133/48


Implementing Interface Methods

◼ Methods declared in an interface are implemented in


the classes which support that interface

public interface File {


public void open(String name);
public void close();
}

public class TextFile implements File {


public void open(String name) {
// implementation of open method
}
public void close() {
// implementation of close method
}
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 134/48


Syntax
◼ In a class declaration, the naming of the superclass
precedes any interfaces supported by the class:
public class Directory extends Secure implements File {
...
}

◼ Multiple Interfaces:
◼ If a class implements multiple interfaces, the interfaces
are all listed, separated by commas

public class Directory implements File, Secure {


...
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 135/48


Implementing an Interface
◼ A class which implements an interface must
implement every method defined by that interface

◼ If one or more methods is not implemented, Java will


generate a compiler error

◼ Subclasses automatically implement all interfaces that


their superclass implements

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 136/48


Typing and Interfaces
◼ A variable's type can be an interface
◼ Interfaces cannot appear in a new expression

File r = new File(); // Error


File f = new TextFile(); // OK!

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 137/48


Subinterfaces
◼ Interfaces can be extended
◼ Interface hierarchy
◼ The interface which extends another interface inherits
all of its method declarations

interface File {
public void open(String name);
public void close();
}
interface ReadableFile extends File {
public byte readByte();
}
interface WritableFile extends File {
public void writeByte(byte b);
}
interface ReadWriteFile
extends ReadableFile, WritableFile {
public void seek(int position);
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 138/48


Using Interfaces

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 139/48
Naming Conventions for Interfaces
• Make "able" interfaces
– Cloneable, Comparable, List, ...
• Name interfaces using proper nouns and provide
"Impl" implementation of your interfaces
– Bank, BankImpl, BankAccount, BankAccountImpl
• Prefix interface names with "I" and use proper nouns
for your classes
– IBank, Bank, IBankAccount

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 140/48


The Interface Comparable
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 the given object
// produce positive result if this is 'greater' than the given object
int compareTo(Object obj);
}

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 141/48
Case study: Comparable Interface
public class Employee implements Comparable{
private String name;
private double salary;

public Employee(String n, double s) {


name = n;
salary = s;
}

@Override
public int compareTo(Object o) {
Employee emp = (Employee)o;
return this.getName().compareTo(emp.getName());
}
}
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 142/48
Sort Array of Comparable Objects
public class EmployeeSortTest {
public static void main(String[] args) {
Employee[] staffs = new Employee[3];

staffs[0] = new Employee("Harry Hacker", 35000);


staffs[1] = new Employee("Carl Cracker", 75000);
staffs[2] = new Employee("Tony Tester", 38000);

Arrays.sort(staffs);

// print out information about all Employee


for (Employee e : staffs)
System.out.println("Name = " + e.getName()
+ ", Salary = " + e.getSalary());
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 143/48


Sort Array using Comparator Interface
public class Employee {
private String name;
private double salary;
public Employee(String n, double s) {
name = n; salary = s;
}
} public class EmployeeSortTest {
public static void main(String[] args) {
Employee[] staffs = new Employee[3];
staffs[0] = new Employee("Harry Hacker", 35000);
staffs[1] = new Employee("Carl Cracker", 75000);
staffs[2] = new Employee("Tony Tester", 38000);
Arrays.sort(staffs, new Comparator<Employee>() {
public int compare(Employee o1, Employee o2) {
return o1.getName().compareTo(o2.getName());
}
});
// print out information about all Employee
for (Employee e : staffs)
System.out.println("Name = " + e.getName()
+ ", Salary = " + e.getSalary());
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 144/48


BÀI TẬP
◼ Cho sơ đồ cây phân cấp như sau:
Nguoi NhanVien

ten : String luong : double PhongBan


namSinh: int ngaynhanviec: Date
PBK: PhongBan maPB : String
tenPB: String

NVQuanLy
SinhVien NhanVienCLCao
phucapChucVu : double
diem1: float trinhdo: String
diem3: float nganh: String
diem3: float noiDaoTao: String GiangVien

thulaoGG : double

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 145/48
BÀI TẬP
◼ Xây dựng các lớp theo sơ đồ cây phân cấp thừa kế,
Xây dựng lớp TruongDaiHoc để thực hiện các yêu
cầu sau
◼ In ra danh sách các sinh viên
◼ In ra danh sách các nhân viên
◼ In ra danh sách lương của nhân viên
◼ Tính lương của tất cả các nhân viên
◼ Với lương nhân viên quản lý = lương + phụ cấp chức vụ
◼ Với lương của giảng viên = lương + thù lao giảng dạy.
◼ Tìm nhân viên có tiền lương cao nhất.
◼ Viết phương thức kiểm tra Người có phải là sinh viên
hay không?
Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 146/48
Inner Class
Inner Class
◼ Inner classes let you define one class within
another. Just as classes have member variables
and methods
◼ Sometimes, though, you find yourself designing
a class where you discover you need behavior
that belongs in a separate, specialized class,
but also needs to be intimately tied to the class
you’re designing
◼ Event handlers (Szwing) are perhaps the best
example of this

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 148/48
Regular Inner Class
◼ Declare inner class

class MyOuter {
class MyInner { }
}

◼ When compile MyOuter, It creates two classes


MyOuter.class and MyOuter$MyInner.class

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 149/48
Regular Inner Class (cont.)
class MyOuter {
private int x = 7;
// inner class definition
class MyInner {
public void seeOuter() {
System.out.println("Outer x is " + x);
}
} // close inner class definition
} // close outer class

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 150/48
Anonymous Inner Classes
◼ Inner classes declared without any class name are
called anonymous
◼ You can even define anonymous classes within an
argument to a method

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 151/48
Example Inner Classes
class Popcorn {
public void pop() {
System.out.println("popcorn");
}
declare a new class which has no
} name, but which is a subclass of
class Food { Popcorn

Popcorn p = new Popcorn() {


public void pop() { Overriding the pop()
method
System.out.println("anonymous popcorn");
}
};
End of the anonymous class definition
}

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 152/48
Example Inner Classes
interface Cookable { Anonymous Inner
public void cook(); Classes with Interface
}
class Food {
Cookable c = new Cookable() {
public void cook() {
System.out.println("anonymous cookable implementer");
}
};
}

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 153/48
Conversion of Data Types
◼ Two kinds of Conversion of Data Types
◼ Conversion of Primitive Data Types

◼ Conversion of Reference Data Types

◼ Conversion of Data Types


◼ Implicit type conversion: The programmer does

not make any attempt to convert the type


◼ Explicit type conversion: Conversion is initiated

by the programmer by making an explicit request


for conversion (type casting)

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 154/48
Conversion of Data Types
◼ Assignment Conversion
<sourceType> s = new <sourceType>();
<targetType> t = s; // Implicit conversion of
<sourceType> to <targetType>
◼ Method Call Conversion

◼ Arithmetic Conversion

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 155/48
Implicit Primitive Type Conversion
◼ Two general rules for implicit primitive type conversion
are 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


narrowing—that is, the size of the target type is
greater than or equal to the size of the source type.

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 156/48
Implicit Primitive Type Conversion
public class ConversionToWider{
public static void main(String[] args) {
int i = 15;
short s = 10;
s= i; Error: Illegal conversion

System.out.println("Value of i: " + i );
}
}

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 157/48
Implicit Primitive Type Conversion

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 158/48
Explicit Primitive Type Conversion
◼ In a narrowing conversion, casting is
mandatory
◼ However, casting to a narrower type runs the
risk of losing information and generating
inaccurate results
◼ You cannot cast a boolean to a non-boolean
type.
◼ You cannot cast a non-boolean type to a
boolean type.

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 159/48
Reference Data Types Conversion
 Cho phép chuyển đổi kiểu dữ liệu tham chiếu (đối tượng)
 Việc chuyển đổi này chỉ tương thích trong quan hệ kế thừa
(dựa vào cây phân cấp kế thừa)
 Upcast
▪ Là khả năng nhìn nhận đối tượng thuộc lớp con như là một
đối tượng thuộc lớp cha (đi lên trên cây phân cấp kế thừa)
→ Có thể chuyển đổi tự động một thực thể của lớp con
sang thực thể của lớp cha (đổi kiểu ngầm định)
 Downcast
▪ Là khả năng nhìn nhận một đối tượng thuộc lớp cha như
một đối tượng thuộc lớp con (đi xuống cây phân cấp kế
thừa)→ Có thể chuyển đổi thực thể của lớp cha thành thực
thể lớp con nhưng phải áp dụng đổi kiểu tường minh
▪ Đây là quy trình rắc rối hơn và có nhiều điểm không an toàn

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 160/48
Reference Data Types Conversion
◼ public class Animal {
public void eat() { // ... }
}
public class Cat extends Animal {
public void eat() { // ... }
public void meow() { // ... }
}
Cat cat = new Cat();
Animal animal = cat;
-------------------
animal = (Animal) cat;
-----------------------
Animal animal = new Cat();

Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 161/48

You might also like