Part 05 - Object Oriented Programming_2025
Part 05 - Object Oriented Programming_2025
◼ Creating Objects
◼ Using Methods
◼ Defining a Method
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
◼ 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
◼
◼ 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
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 13/48
Class Example
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
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.
+flipVertical()
+flipHorizontal()
Shape
+draw()
+erase()
+move()
+setColor()
+getColor()
created object.
◼ Objects are manipulated via references
◼ Invoke object’s methods:
<object reference>.<method_name>(<arguments>)
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
// class body
}
Class instantiation
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
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
◼ Overloading
◼ When there are a number of constructors with
different parameters
◼ Constructors are commonly overloaded to allow
for different ways of initializing instances
BankAccount knownAccount =
new BankAccount(accountNumber);
BankAccount namedAccount =
new BankAccount("My Checking Account");
public BankAccount() {
this("TestName");
}
package com.megabank.models;
Access Levels
private Y N N N
no specifier Y Y N N
protected Y Y Y N
public Y Y Y Y
account.debit(50.5)
parameters
receiver
message
return method
access type name parameter list
modifier
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
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
◼ 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;
}
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
Khoa
KhoaCNTT
CNTT –– Trường
ĐH NôngĐH Nông
Lâm Lâm01/2016
TP. HCM TP. HCM 67/48
Defining Methods
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;
}
}
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
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
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
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
◼ 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
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 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
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
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
//application code
...
Employee e = new Employee();
e.setName("John"); call to Person’s setName() method
System.out.print(e.getName());
e.setSalary(3.0);
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
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.
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
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
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
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;
}
}
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
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
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
◼ Examples: +area()
+perimeter()
+area()
+perimeter()
+area()
+perimeter()
Shape CartesianPoint
# CartesianPoint location - int x
- int y
+ double area()
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
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.”
<<interface>>
Comparable
+compareTo()
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
}
◼ Multiple Interfaces:
◼ If a class implements multiple interfaces, the interfaces
are all listed, separated by commas
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
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
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;
@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];
Arrays.sort(staffs);
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 { }
}
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
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
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
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