2. 1. Why OOP?
Traditional Programming Language (C, Pascal)
Object-Oriented Programming Language
2. Class Instance
Class Compartment
Creating a Class
Creating an Instance
3. Method of Class
Creating a Method
Constructor
Information Hiding Encapsulation
Overloading Method
4. Helpful Reminder
5. Exercise and Homework
2
46. Java is an Object Oriented Language. As a language
that has the Object Oriented feature Java supports
the following fundamental concepts:
Polymorphism
Inheritance
Encapsulation
Abstraction
Classes
Objects
Instance
Method
Message Parsing
6
47. Notable drawbacks for creating
reusable software components:
Programs are made up of
functions. Functions are often not
reusable. It is very difficult to
copy a function from one
program and reuse in another
program because the function is
likely to reference the headers,
global variables and other
functions.
Not suitable of high-level
abstraction for solving real life
problems.
7
48. The basic unit of OOP is a
class, which encapsulates
both the static attributes
and dynamic behaviors
within a box, and
specifies the public
interface for using these
boxes.
8
OOP languages permit higher level of abstraction for
solving real-life problems. The OOP languages (such as
Java, C++, C#) let you think in the problem space, and use
software objects to represent and abstract entities of the
problem space to solve the problem.
62. ចន
10
Object-Oriented technology has many benefits:
• EEEEaaaasssseeee iiiinnnn ssssooooffffttttwwwwaaaarrrreeee ddddeeeessssiiiiggggnnnn as you could think in the problem space rather than the
machine's bits and bytes. You are dealing with high-level concepts and
abstractions. Ease in design leads to more productive software development.
• EEEEaaaasssseeee iiiinnnn ssssooooffffttttwwwwaaaarrrreeee mmmmaaaaiiiinnnntttteeeennnnaaaannnncccceeee: object-oriented software are easier to understand,
therefore easier to test, debug, and maintain.
• RRRReeeeuuuussssaaaabbbblllleeee ssssooooffffttttwwwwaaaarrrreeee: you don't need to keep re-inventing the wheels and re-write the
same functions for different situations. The fastest and safest way of developing a
new application is to reuse existing codes - fully tested and proven codes.
63. A class is a blueprint[បង], template[ពម ], or prototype[
គ
64. ] that defines and describes the static attributes
and dynamic behaviors common to all objects of the
same kind.
An instance is an instantiation of a class. All the
instances of a class have similar properties, as
described in the class definition.
For example, you can define a class called Student and
create three instances of the class Student for Peter,
Paul and Pauline.
The term object usually refers to instance.
11
65. A class can be visualized as
a three-compartment box:
Name
Variables
Methods
12
67. The following figure shows two instances of the
class Student, identified as paul and perter.
14
68. [AccessControlModifier] class ClassName {
// class body contains definition of variables and methods
...
}
15
Class Naming Convention:
A class name shall be a noun, or a noun phrase made up of
several words.
All the words shall be initial-capitalized (camel-case).
Use a singular noun for class name.
Choose a meaningful and self-descriptive classname.
▪ For examples:
SoccerPlayer, HttpProxyServer, FileInputStream, PrintStream
and SocketFactory.
70. Variable Naming Convention:
A variable name shall be a noun, or a noun phrase
made up of several words.
The first word is in lowercase and the rest of the words
are initial-capitalized,
▪ e.g., theFontSize, roomNumber, xMax, yMin and
xTopLeft.
▪ Take note that variable name begins with an
lowercase, while class name begins with an
uppercase.
17
72. To create an instance of a class, you have to:
Declare an instance identifier (instance name) of a
particular class.
Construct the instance (i.e., allocate storage for the
instance and initialize the instance) using the new
operator.
19
73. The variables and methods belonging to a class are formally called
member variables and member methods.
To reference a member variable or method, you must:
Identify the instance you are interested in, and
Reference the method or variable via the dot operator.
20
In general, suppose there is a class called AClass with a member variable
called aVariable and a member method called aMethod(). An instance
called anInstance is constructed for AClass. You use anInstance.aVariable
and anInstance.aMethod().
78. A method:
receives parameters from the caller,
performs the operations defined in the method body, and
returns a piece of result (or void) to the caller.
Syntax:
[AccessControlModifier] returnType methodName ([argumentList]) {
// method body or implementation
......
}
Example:
public double getArea() {
double area = radius * radius * Math.PI;
return area;
}
23
79. A method name shall be a verb, or a verb phrase
made up of several words.
The first word is in lowercase and the rest of the
words are initial-capitalized.
For example, getRadius(), getParameterValues().
Note:
variable name is a noun
method name is a verb
Methods take arguments in parentheses (possibly zero
argument with empty parentheses), but variables do not.
24
90. A constructor is a special method that has the same method name as the class
name. It is used to initialize the instance constructed.
To create a new instance of a class, you need to use a special new operator
followed by a call to one of the constructors.
Circle c1 = new Circle();
Circle c2 = new Circle(2.0);
Circle c3 = new Circle(3.0, red);
A constructor is different from an ordinary method in the following aspects:
The name of the constructor method is the same as the class name, and
begins with an uppercase.
Constructor has no return type (or implicitly returns void). Hence, no return
statement is allowed inside the constructor's body.
Constructor can only be invoked via the new operator. It can only be used
once to initialize the instance constructed. You cannot call the constructor
afterwards.
Constructors are not inherited (to be explained later).
29
93. Member variables of a class are typically private
They are hidden from the outside world (i.e., the other
classes)
Access to the member variables are provided via the public
assessor methods, e.g., getRadius() and setRadius().
This follows the principle of information hiding.
Objects communicate with each others using well-defined
interfaces.
Objects are not allowed to know the implementation details of
others.
Note: Do not make any variable public, unless you have a
good reason.
31
94. Mutator/Setter:
Any method that changes a property of an object,
normally setXXX() methods.
public void setName(String name)
public void setAge(int age)
Accessor:
It is a method that returns a property of an object,
normally getXXX() methods.
public String getName()
public int getAge()
32
95. An access control modifier can be used to control the
visibility of a class, or a member variable or a
member method within a class.
public: The class/variable/method is accessible and
available to all the other objects in the system.
private: The class/variable/method is accessible and
available within this class only.
UML Notations: In UML notations, public entity is
denoted with a +, while private entity is denoted
with a - in the class diagram.
More access control modifiers will be discussed later.
33
96. You can use keyword this to refer to this class/instance inside
a class definition.
One of the main usage of keyword this is to resolve ambiguity
[Eពម,នចF##].
34
99. Every well-designed Java class should have a public method called toString() that
returns a string description of the object.
You can invoke the toString() method explicitly by calling
anInstanceName.toString() or
implicitly via println() or
String concatenation operator '+'.
Running println(anInstance)
37
100. 38
Rectangle
-width: int
-heigh: int
create+Rectangle(width: int, heigh: int)
+getWidth(): int
+setWidth(width: int)
+getHeigh(): int
+setHeigh(heigh: int)
+getArea(): int
Student
-name: String
-grade: double
create+Student(name: String, grade: double)
+getName(): String
+setName(name: String)
+getGrade(): double
+setGrade(grade: double)
+toString(): String
116. import java.awt.Point;
class Box {
int x1 = 0; // these 4 variables
int y1 = 0; // are instance variable
int x2 = 0; //
int y2 = 0; // (default is package)
Box buildBox(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
return this;
}
Box buildBox(Point topLeft, Point bottomRight) {
x1 = topLeft.x;
y1 = topLeft.y;
x2 = bottomRight.x;
y2 = bottomRight.y;
return this;
}
Box buildBox(Point topLeft, int w, int h) {
x1 = topLeft.x;
y1 = topLeft.y;
x2 = (x1 + w);
y2 = (y1 + h);
return this;
}
This method takes four integer
arguments and returns a reference
to the resulting Box object.
Because the arguments have the
same names as the instance
variables, the keyword this is used
inside the method when referring
to the instance variables.
You can overload buildBox()
by creating a second version of
the method with an argument
list that takes two Point
objects:
Another possible way to define the
rectangle is to use a top corner, a
height, and a width:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
3 Methods are overloaded
41
117. void printBox(){
System.out.print(Box: + x1 + , + y1);
System.out.println(, + x2 + , + y2 + );
}
public static void main(String[] arguments) {
Box rect = new Box();
System.out.println(Calling buildBox with coordinates
+ (25,25) and (50,50):);
rect.buildBox(25, 25, 50, 50);
rect.printBox();
System.out.println(nCalling buildBox with points
+ (10,10) and (20,20):);
rect.buildBox(new Point(10, 10), new Point(20, 20));
rect.printBox();
System.out.println(nCalling buildBox with 1 point
+ (10,10), width 50 and height 50:);
rect.buildBox(new Point(10, 10), 50, 50);
rect.printBox();
}
}
This method is to
display the rectangle’s
coordinates, and a
main() method tries
everything out.
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
55:
57:
42
118. void printBox(){
System.out.print(Box: + x1 + , + y1);
System.out.println(, + x2 + , + y2 + );
}
public static void main(String[] arguments) {
Box rect = new Box();
System.out.println(Calling buildBox with coordinates
+ (25,25) and (50,50):);
rect.buildBox(25, 25, 50, 50);
rect.printBox();
System.out.println(nCalling buildBox with points
+ (10,10) and (20,20):);
rect.buildBox(new Point(10, 10), new Point(20, 20));
rect.printBox();
System.out.println(nCalling buildBox with 1 point
+ (10,10), width 50 and height 50:);
rect.buildBox(new Point(10, 10), 50, 50);
rect.printBox();
}
}
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
55:
57:
Create a Box’s instance, rect.
This line of code calls to the
default constructor.
43
119. void printBox(){
System.out.print(Box: + x1 + , + y1);
System.out.println(, + x2 + , + y2 + );
}
public static void main(String[] arguments) {
Box rect = new Box();
System.out.println(Calling buildBox with coordinates
+ (25,25) and (50,50):);
rect.buildBox(25, 25, 50, 50);
rect.printBox();
System.out.println(nCalling buildBox with points
+ (10,10) and (20,20):);
rect.buildBox(new Point(10, 10), new Point(20, 20));
rect.printBox();
System.out.println(nCalling buildBox with 1 point
+ (10,10), width 50 and height 50:);
rect.buildBox(new Point(10, 10), 50, 50);
rect.printBox();
}
}
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
55:
57:
rect is built by calling the method of
the class Box on line 9
44
120. void printBox(){
System.out.print(Box: + x1 + , + y1);
System.out.println(, + x2 + , + y2 + );
}
public static void main(String[] arguments) {
Box rect = new Box();
System.out.println(Calling buildBox with coordinates
+ (25,25) and (50,50):);
rect.buildBox(25, 25, 50, 50);
rect.printBox();
System.out.println(nCalling buildBox with points
+ (10,10) and (20,20):);
rect.buildBox(new Point(10, 10), new Point(20, 20));
rect.printBox();
System.out.println(nCalling buildBox with 1 point
+ (10,10), width 50 and height 50:);
rect.buildBox(new Point(10, 10), 50, 50);
rect.printBox();
}
}
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
55:
57:
print the information of rect by
calling the method on line 32
45
121. void printBox(){
System.out.print(Box: + x1 + , + y1);
System.out.println(, + x2 + , + y2 + );
}
public static void main(String[] arguments) {
Box rect = new Box();
System.out.println(Calling buildBox with coordinates
+ (25,25) and (50,50):);
rect.buildBox(25, 25, 50, 50);
rect.printBox();
System.out.println(nCalling buildBox with points
+ (10,10) and (20,20):);
rect.buildBox(new Point(10, 10), new Point(20, 20));
rect.printBox();
System.out.println(nCalling buildBox with 1 point
+ (10,10), width 50 and height 50:);
rect.buildBox(new Point(10, 10), 50, 50);
rect.printBox();
}
}
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
55:
57:
Now, a box
is built by a
method on
line 17
46
122. void printBox(){
System.out.print(Box: + x1 + , + y1);
System.out.println(, + x2 + , + y2 + );
}
public static void main(String[] arguments) {
Box rect = new Box();
System.out.println(Calling buildBox with coordinates
+ (25,25) and (50,50):);
rect.buildBox(25, 25, 50, 50);
rect.printBox();
System.out.println(nCalling buildBox with points
+ (10,10) and (20,20):);
rect.buildBox(new Point(10, 10), new Point(20, 20));
rect.printBox();
System.out.println(nCalling buildBox with 1 point
+ (10,10), width 50 and height 50:);
rect.buildBox(new Point(10, 10), 50, 50);
rect.printBox();
}
}
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
55:
57:
Now, aa bbooxx iiss bbuuiilltt
by a method on
line 25
47
123. A final primitive variable cannot be re-assigned a
new value.
A final object cannot be re-assigned a new address.
A final class cannot be sub-classed (or extended).
A final method cannot be overridden.
48
124. public static Double add(Double a, Double b) {
return a + b;
}
. . .
int a = 1;
int b = 2;
double c = 3;
double d = 4;
System.out.println(add(a, b)); // invalid
System.out.println(add(c, d)); // OK
49
137. f`
TTTToooo ppppaaaarrrraaaammmmeeeetttteeeerrrriiiizzzzeeee ccccooooddddeeee :::: In addition to making reusable code that is the
same in all cases, you will often want to use parameters that change the
way the method works.
ie
141. FFFFoooorrrr ttttoooopppp--ddddoooowwwwnnnn pppprrrrooooggggrrrraaaammmmmmmmiiiinnnngggg :::: A very useful style of programming is called top-down
51
programming. You solve a big problem (the top) by breaking it down
into little problems. To do this in a program, you write a method for solving
your big problem by calling on other methods to solve the smaller parts of the
problem. And these methods for solving the simpler problems similarly call on
other methods until you get down to simple methods which solve simple
problems
ប
145. Zប˜™
7ច]
TTTToooo ccccrrrreeeeaaaatttteeee ccccoooonnnncccceeeeppppttttuuuuaaaallll uuuunnnniiiittttssss :::: Create methods to do something that is one
action in your mental view of the problem. This will make it much easier for
you to work with your programs.
Method មយ Bpប
148. 1. Don’t try to invent the wheel,
When possible, reuse the Java
API classes and methods. This
reduce program development
time and avoid introducing
programming errors.
2. To promote software reusability,
every method should be limited
to performed a single, defined
task, and name of the method
should express that task
effectively. Such methods make
programs easier to write, debug,
maintain and modify.
3. All small method that performs
one task is easier to test and
debug than a larger method
that performs many tasks.
1. កJពœ€មប
169. 4. Class Math is part of java.lang
package, which is implicitly
imported by the compiler, so it is
not necessary to import class
Math to use its methods.
5. Methods that modify the values
of private variables should verify
that that intended new values
are proper. If they are not, the
set methods should place the
private variables into an
appropriate consistent state.
6. The online Java API
documentation is easy to search
and provides many details about
each class. As you learn one
class, you should get in the habit
of looking a the class in the
online documentation for
additional information.
4. Class MMMMaaaatttthhhh Zផកមយ¥ន jjjjaaaavvvvaaaa....llllaaaannnngggg
package U8
LM;ន import
185. A method that has many parameters my be performed too many tasks. Consider dividing the method into
smaller methods that perform separate tasks. As a guideline, try to fit the method header on one line if
possible.
public void doThisAndDoThat(int a, int b, String str, boolean isOK, char c,
float f, double d, int[] someArray, boolean success)
Declaring a method outside the body of a class declaration or inside the body of another method is a
syntax error.
public class Monkey {
public void cry() {
public void eat() { . . . } error! Method can not be in a method
}
}
public void jump() { . . . } error! Method cannot be outside class
Omitting return-value type in a method declaration is a syntax error.
public void methodA(int a) { . . . } error! no return type
54
186. Placing a semicolon after the right parenthesis enclosing the parameter
list of a method declaration is a syntax error.
public void methodA(int a) ; error here
{
. . .
}
Redeclaring a method parameter as a local variable in the method’s
body is a compilation error.
public void methodA(int a) {
int a; // error here
}
55
187. Forgetting to return a value from a method that should return a value is a compilation
error. If a return-value type other than void is specified, the method must contain a
return statement that returns a value consistent with the method’s return-value type.
Returning a value from a method whose return type has been declared void is a
compilation error.
public int addition(int a, int b) {
int total = a + b;
return total; error! if you forget this statement
}
public int addition(int a, int b) {
float total = a + b;
return total; error!
}
public void doSomething(int a, int b) {
int total = a + b;
return total; error!
}
56
188. Add one construction to the following class:
class Car {
private String color;
private int width;
private int height;
private String brandName;
private String countryName;
// add one constructor
}
// In NetBeans: Alt + Insert
57
189. Write the Author
class. Also write a
test program called
TestAuthor to test
the constructor and
public methods.
58
Author
-name: String
-email: String
-gender: char
create+Author(name: String, email: String, gender: char)
+getGender(): char
+setGender(gender: char)
+getName(): String
+setName(name: String)
+getEmail(): String
+setEmail(email: String)
+toString(): String
Try changing the email of an author, e.g
Author anAuthor = new Author(Tan Ah Teck, ahteck@somewhere.com, 'm');
System.out.println(anAuthor); // call toString()
anAuthor.setEmail(paul@nowhere.com)
System.out.println(anAuthor);
190. Book Author
-name: String
-author: Author
-price: double
-qtyInStock: int = 0
create+Book(name: String, author: Author, price: double)
create+Book(name: String, author: Author, price: double, qtyInStock: int)
+getQtyInStock(): int
+setQtyInStock(qtyInStock: int)
+getName(): String
+setName(name: String)
+getAuthor(): Author
+setAuthor(author: Author)
+getPrice(): double
+setPrice(price: double)
+toString(): String
Write the class Book (which uses the Author class written earlier). Also write a test program called
59
TestBook to test the constructor and public methods in the class Book.
Take Note that you have to construct an instance of Author before you can construct an instance of
Book. E.g.,
Author anAuthor = new Author(......);
Book aBook = new Book(Java for dummy, anAuthor, 19.95, 1000);
// Use an anonymous instance of Author
Book anotherBook = new Book(more Java for dummy, new Author(......), 29.95, 888);
191. You are required to:
1. Write the code for the class MyPoint. Also write a test program (called
TestMyPoint) to test all the methods defined in the class.
// Overloading method distance()
// this version takes two ints as arguments
public double distance(int x, int y) {
int xDiff = this.x – x;
int yDiff = ......
return Math.sqrt(xDiff*xDiff + yDiff*yDiff);
}
// this version takes a
// MyPoint instance as argument
public double distance(MyPoint another) {
int xDiff = this.x – another.x;
.......
}
//Test program
MyPoint p1 = new MyPoint(3, 0);
MyPoint p2 = new MyPoint(0, 4);
......
//Testing the overloaded method distance()
System.out.println(p1.distance(p2)); // which version?
System.out.println(p1.distance(5, 6)); // which version?
.....
60
MyPoint
-x: int = 0
-y: int = 0
create+MyPoint()
create+MyPoint(x: int, y: int)
+getY(): int
+setY(y: int)
+getX(): int
+setX(x: int)
+toString(): String
+distance(x: int, y: int): double
+distance(another: MyPoint): double
192. 61
2. Write a program that allocates 10 points in an array of MyPoint, and initializes to (1,
1), (2, 2), ... (10, 10).
Hints: You need to allocate the array, as well as each of the ten MyPoint instances.
// Declare and allocate an array of MyPoint
MyPoint[] points = new MyPoint[10];
for (......) {
points[i] = new MyPoint(...); // Allocate each of MyPoint instances
System.out.println(points[i]);
}
193. Write the MyCircle class. Also write a test program (called
TestMyCircle) to test all the methods defined in the class.
62
194. Write the MyTriangle class. Also write a test
program (called TestMyTriangle) to test all the
methods defined in the class.
63