This class is abstract but it does not provide implementation of abstract method print(). An abstract class must be subclassed and the abstract methods must be implemented in the subclass. We cannot create an object of an abstract class directly, it has to be through its concrete subclass.
2. Why should we study this lecture?
This lecture will
Help you reviewing basic concepts of the object-
oriented paradigm.
Supply syntax for declaring a Java class. It can
be a normal class, a sub-class, a nested class,
abstract class or an interface.
Supply ways to use Java classes.
2
3. Review
Object: đối tượng, những sự vật, hiện tựợng cụ thể
mà con người sờ có cảm xúc về nó. Thí dụ cái xe
máy Air Blade cụ thể mà ta đang dùng
Class: lớp, là một tập các đối tượng tương tự nhau.
Con người thường dùng các danh từ chung (như xe
gắn máy) để đặt tên gọi cho một class.
Modifiers are Java keywords that give the compiler
information about the nature of code (methods), data,
classes
Access Modifiers: public, protected, private and no-
modifier (default)
Other modifiers: final, abstract, static, native,
transient, synchronized, volatile
3
4. Review
Type conversion = implicit type change
Type casting = explicit type change
Conversion allows widening type change only.
If we want a narrowing type change, we must use
an explicit casting.
Object type conformity:
fatherReferene=sonReference;
4
5. Review
Exceptions: Errors beyond the control of a program. When an
exception occurs, the program will terminate abruptly.
Exception can be caught by the try..catch..finally statement
Assertions enables the programmer to test assumptions about
the program. Assertions are introduced in Java 1.4. From Java
1.5, it is removed.
Ways of writing assertion statements are:
assert expression;
assert expression1:expression2;
Compiling a program having assertion statement:
javac –source 1.4 FileName
Running a program with assertion
java –ea Package.FileClass
java –enableassertions Package.FileClass
5
6. Review
-Knowledge from the subject OOP:
- What are methods and constructors.
- Order of memory allocations, order of executions of
constructors.
6
7. Objectives
Introduction to OO Paradigm
Benefits of OO Implementation
How to declare a class
How to use a class
How to declare a subclass
Your homework: Workshop 2 (with report)
You are requested to complete the case stydy 1 introduced
at the slide 22
Assessment: the next class
7
8. Contents
6.1- Introduction to OO Paradigm
6.2- Benefits of OO Implementation
6.3- Hints for class design
6.4- Declaring/ Using a class
6.5- Case study 1 (Managing a list of persons)
6.6- Inheritance Demonstration
6.7- Variable-length argument list
6.8- Some Tests
6.9- Nested Classes
6.10- Interfaces
6.11- Abstract Classes
6.12- Anonymous Classes
6.13- Enum Types
You are
introduced in
the subject OOP
8
9. 6.1- Introduction to OOP
Procedure-Oriented
Program
data1
data2
Function1 (data1)
Function2 (data1)
Function3
(data2)Function4
(data2)
Class A
{
}
data1
Function1 ()
Function2 ()
Class B
{
}
data2
Function3 ()
Function4()
Modifiers
Modifiers
Object = Data +
Methods
Basic
Concepts
-
Encapsulation
- Inheritance
-
Polymorphis
Particular
methods:
Constructor
s Constructor: a specific method which
is automatically called when an object
is created.
9
10. Introduction to OOP
Why OOP is introduced?
It is a easy way to describe objects in nature.
It supports
Ability to describe relationship between objects especially,
the “is a kind of” relationship The problem is described
easier and better Inheritance
Security in code Modifiers
Ability to maintain code Encapsulation
Polymorphism overloading/overriding methods
…
10
11. 6.2- Benefits of OO Impl.
Encapsulation: Aggregation
of data and behavior.
Data of a class should be
hidden from the outside. The
outside access them by
getters/setters
All behavior should be
accessed only via methods.
A method should have a
boundary condition. The if
statement is commonly used to
ensure that this access is valid
or data of the object are valid
at any time.
class A
{
}
data1
Function1 ()
Function2 ()
Modifiers
Behavior: hành vi, ability of an
object which is identified and given
a name (verb).
Method: Phương thức, cách thức để
làm: Implementation of a behavior.
11
12. Benefits of OO Impl….
Inheritance: Ability allows a class having members of an
existed class Re-used code.
ID_Num
name
yearOfBirth
address
getID_Num()
setID_Num(newID)
......
class PERSON
rollNum
score
getScore()
setSore(newScore)
......
class STUDENT
“is a”
relationshi
p
ID_Num
name
yearOfBirth
address
getID_Num()
setID_Num(newID)
......
class STUDENT
rollNum
score
getScore()
setSore(newScore)
......
inherited
extensions
Son = Father + extensions12
13. Benefits of OO Impl.…
How to implement Inheritance?
Electric Products< code, name, make, price, guaranty, voltage, power>
Ceramic Products < code, name, make, price, type >
Food Products < code, name, make, price , date, expiredDate >
Product
code
name
make
price
ElectricProduct
guaranty
voltage
power
Ceramic
type
Food
date
expiredDate
The father class
is implemented
first then it’s
subclasses
afterwards
intersection
rest
13
14. Benefits of OO Impl.…
Order of object creations:
(1) Memory block containing data inherited
from Father is allocated first.
(2) Memory block containing extension data is
allocated afterward.
GrandFather obj1 = new GrandFather();
Father obj1 = new Father();
Son obj2 = new Son();
Data gf
Data f
obj1: 1000
obj2: 800
obj3: 500
100
0
800
500
Data s
Step 1
Step 2
Data gf
Data f
Data gfStep 1
Step 2
Step 3
14
15. Benefits of OO Impl…
Polymorphism: Ability allows many versions of a method
based on overloading and overriding methods techniques.
15
16. 6.3- Hints for class design
Coupling
Is an object’s reliance on
knowledge of the internals of
another entity’s implementation.
When object A is tightly coupled
to object B, a programmer who
wants to use or modify A is
required to have an inappropriately
extensive expertise in how to use
B.
Head
Eye1
Eye2
High
coupling
( Bad
design)
Head
leftEye
rightEye
Eye
Eye
Low coupling
( Good design)
16
17. Hints for class design
Cohesion is the degree to which a class or method resists
being broken down into smaller pieces.
classA
M()
{
}
Operation 1
Operation 2
Low
cohession
( Bad design)
classA
M1()
{
}
M2()
{
}
M()
{ M1(); M2();
}
Operation 1
Operation 2
High cohesion
( Good design)17
18. 6.4- Declaring/Using a Class
[public] class ClassName [ extends FatherClass] {
[modifier] DataType dataMember [=InitialValue];
[modifier] ClassName [(args)] // constructors
{ super (args); // call to the constructor of FatherClass – first line
<code>
}
[ modifier] ReturnType methodName (args)
{ <code >
super.Method(args); // call to a method of FatherClass
}
}
// Creating an object
ClassName obj= new ClassName (args);
obj.Method(args);
Data of
Object
obj:
12000
12000
Getters
public Type getField()
Setters
public void
setField(arg)
WHY
?
What is the keyword super
used?
18
19. Key Points: Overloading Methods
A method that has an identical name and identical
number, types, and order of arguments.
Overloading methods are implemented in the same
class.
Overloading methods are the same name but their
arguments have differences.
19
20. Key points: Overriding methods
A method that has an identical name and
identical number, types, and order of arguments
as a method in a parent class is an overriding
method.
Each parent class method may be overridden
once at most in any one subclass.
An overriding method must return exactly the
same type as the method it overrides.
20
21. Overriding methods…
An overriding method must not be less
accessible than the method it overrides.
An overriding method must not throw any
checked exception (or subclasses of those
exceptions) that are not declared for the
overridden method.
An overridden method is completely replaced
by the overriding method unless the overridden
method is deliberately (cố ý) invoked from within
the subclass.
21
22. 6.5- Case study 1
To develop a program, steps must be followed:
Analysis
Design
Writing Report
Implement
Test
Goals of this case study is providing a sample
for writing a report including 2 first steps in your
notebook for each problem you are requested
to solve.
22
23. Report
1- Problem
Each person details include code, name, and age.
Write a Java program that allows users adding a new
person to the list, removing a person having a known
code from the list, updating details of a known-code
person, listing all managed persons in descending
order of ages using a simple menu.
23
24. Report…
1- Problem
….
2- Analysis
From the problem description. The following concepts will be
implemented as appropriate classes:
Class Person
Description for a person
Data: String code; String name; int age
Methods:
Constructors
Getters, setters
void input() for collecting data
String toString() to get data in string format
24
25. Report…
Class PersonList
Description for a list of persons
Data:
Person[] list; // current list
int count // current number of persons
Methods:
Constructors
Getters, setters
void add(); // add a new person. Data are collected from keyboard
int find (String aCode); // Find the index of the person whose code is known
void remove()// remove a person. His/ her code is accepted from keyboard
void sort(); // descending sort the list based on their ages
void update(); // update a person, data are accepted from keyboard
void print(); // print the list
25
26. Report…
Class Menu
Description for a menu
Data
String[] hints; // list of hints
int n; // current number of hints
Methods:
Menu(int n): constructor for initializing a menu containing n options
void add (String aHint); // add an option
int getChoice(); // get an option
Class ManagingProgram1
Description for the program
Data: none
Methods:
main(…): main method of the program
26
45. Some Tests
a) A7500
b) 500A7
c) 500
d) None of the
others
Compile-time error
( static code can not
access instance variables)
45
46. Some Tests
a) A1210
b) 10A12
c) 17
d) None of the
others
Compile-time error
( The y variable is out of
scope)
46
47. A summary
- Introduction to OO Paradigm
- Benefits of OO Implementation
- Hints for class design
- Declaring/ Using a class
- Identifying a class:
- Main noun Class
- Descriptive nouns Data/ constants
- Verbs Behaviors Methods
- Implementing a class
- Constructors
- Methods
- Getters, setters
- Methods accepting variable-length argument list
47
48. 6.9- Inner-Nested classes
Class is declared inside some
other class or inside the body of
other class’s method.
2 types of nested class: Static
Nested classes, Inner classes (
non-static)
Static nested class All
objects belong to the outer class
share one nested object(cặp song
sinh dính nhau, phần dính nhau nằm
ở bên ngoài).
Inner class: Each outer object
has it’s own inner object Outer
object must contain an instance
of the inner object then accesses
members of this nested instance
(trái tim nằm bên trong thân
người)
obj1
obj2
Static
nested obj
obj1
Inner
obj
obj2
Inner
obj
48
49. Inner-Nested classes…
A nested class violates the
recommendation “low coupling” in class
design. Why are nested classes used?
It is a way of logically grouping classes that
are only used in one place.
It increases encapsulation.
Nested classes can lead to more readable
and maintainable code.
49
50. Static Nested Classes Demo…
Class-level nested
class.
Because the static
nested object is
stored separately
from enclosing
instances, static
nested object can
be initiated without
enclosing objects.
Methods of static nested class can not
access data of enclosing instance
because it can created even when
enclosing objects do not exist.
50
51. Inner classes demo…
obj
obj: 2000
x = 5
inner:
3000
y = 7
A method of nested
class can access all
members of its
enclosing class
outerObj
x=5
innerObj
y=7
Error: inner obj do
not created yet.
200
0
300
0
51
52. Creating Inner Class instance through
enclosing instance
obj: 1000
x = 5
in1: 2000
y = 1
in2: 3000
z = 2
200
0
300
0
100
0
52
53. Inner Classes
Defined Inside Methods
Local
class
Inner-method
class can not
access normal
local variables
of the
containing
method.
53
54. 6.10- Abstract classes
The result of so-high
generalization.
Use the keyword abstract to
declare an abstract class or
an abstract method.
Abstract method is a
prototype (no body).
An instance of abstract class
can not be created but
concrete objects (all abstract
methods were implemented).
Modified
54
55. Abstract classes…
This class have no abstract method but it is
declared as an abstract class. So, we can not
initiate an object of this class.
55
57. 6.11- Interfaces
Interface: A group of methods prototypes
which will be implemented in a concrete class.
You can not create an instance of an interface.
Access modifier of a method of
an interface can be default but it
must be public in a class
implementing this interface.
Modified
.
57
class A implements Iterafce_1, Interface_2
{ ……………………….}
58. Interfaces…
When is an interface designed? When
methods must be implemented in some classes.
Advantages of interfaces:
A way to make a model (template) for a kind of
applications.
A way for designer controlling implementers.
58
59. 6.12- Anonymous Class
We can initiate concrete objects only (all methods
were implemented and they are not abstract
ones).
Java permits we create directly an object of an
interface or an abstract class if all prototypes and
abstract methods are implemented.
We can not develop a class which implements this
interface or extends the abstract class.
We can not a chance to give a class name to these
code Anonymous class.
When the program is compiled, the class name will
be given by the compiler.
59
61. Anonymous Class…
Anonymous class is a technique is
commonly used to support programmer
when only some methods are overridden
only especially in event programming.
Concrete methods but
they can not be used
because the class is
declared as abstract one.
The abstract class
can be used only
when at least one
of it’s methods is
overridden
61
62. 6.13: Enum Type
It is introduced from Java 1.5.
An enum type is a type whose fields consist of a fixed set
of constants. Common examples include compass
directions (values of NORTH, SOUTH, EAST, and WEST)
and the days of the week. Because they are constants,
the names of an enum type's fields are in uppercase
letters.
Similarities between traditional classes and enums: refer
to the page 198.
Enum type is a group of constants. It is given a name.
Each constant is given a name (name of constant).
62
64. Summary
6.1- Introduction to OO Paradigm
6.2- Benefits of OO Implementation
6.3- Hints for class design
6.4- Declaring/ Using a class
6.5- Case study 1 (Managing a list of persons)
6.6- Inheritance Demonstration
6.7- Variable-length argument list
6.8- Some Tests
6.9- Nested Classes
6.10- Interfaces
6.11- Abstract Classes
6.12- Anonymous Classes
6.13- Enum Types
64