java 2 chapter 10 - basic oop in java

68
Lecture d by: CHEA VICHET 077 657 007 1

Upload: lets-go-to-study

Post on 02-Jul-2015

370 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Java 2   chapter 10 - basic oop in java

Lecture d by: CHEA VICHET

077 657 007 1

Page 2: Java 2   chapter 10 - basic oop in java

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

Page 3: Java 2   chapter 10 - basic oop in java

�ប���កចង�� �ង PC ម�យ��គ�ង ��ក��ន�យក motherboard, processor, RAMs, hard disk, casing, power supply មក3ក4បប567 8�� 9 ��កម:ន4�;ចខ=8> �� RAM ផ8:�@�ប�ទBC Hard Disk ធ�G7ច�ទ! បIJ�នK��ក4�;ច�LM�ន interface �Oម�LM 9 �ប���ក�នIDE Hard Disk ��ក�LM��ន motherboard support IDE.

3

Page 4: Java 2   chapter 10 - basic oop in java

4

� SនកT�LM;នU�� �ងផV�ផWJ ��3យ��គ�ង (component) Z��ច�នU7ចZ chasis, doors, engine, wheels, break, transmission, etc.

� Components �គ4ទJក> reusable, e.g., wheel [ចយក�\��ប�;នZម�យSន�ផVង]�ទ^;ន

� Hardware U7ចZ computers ន:ង cars �LM;នផV�ផWJ �� �ង�3យ��គ�ង �U8�គ�_> reusable components.

Page 5: Java 2   chapter 10 - basic oop in java

5

� ចJ`ច��a` software M bញ? ��ក[ច�ធ=� software application ម�យ�3យ�e �Bយក routine �ន` �e �យBយក routine �f` e�ច�g�យe �ពOង> program U��ន�eie;ន�ទ?

� ច��8�គj �ទ! ម:នU7ច hardware �ទ! kZie8�;កCB ក�JងieផV�ផWJ � application ម�យ�3យ software components 9

� 4បl�ងពb mn o� �មJន �គBe�Be programs ��ច�នpបម:ន�B! �គប application ថrbន:ម�យ] �គ�LMB:កs�B=ងeក e�ច�g�យBe�BeកមrM :ធb4បពbច�នJចB7នtមក

Page 6: Java 2   chapter 10 - basic oop in java

� 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

Page 7: Java 2   chapter 10 - basic oop in java

� 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

Page 8: Java 2   chapter 10 - basic oop in java

� 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.

Page 9: Java 2   chapter 10 - basic oop in java

9

� �ប���កចងBe�Be soccer games ម�យ 9 ��កនOងជ�បie8�;កក�Jងieប�ងv� game ក�Jង procedural languages 9 បIJ�នK OOP languages, [ច�[យ��កប�ងv�កមrM :ធb�3យពOង�ផxក�8�MyJព:] �U8�នក�Jង soccer games. � Player: ▪ Attributes: name, number, location ▪ Operations: run, jump, kick-the-ball

� Ball: � Reference: � Field: � Audience: � Weather:

Page 10: Java 2   chapter 10 - basic oop in java

10

� Classes ម�យច�ន�ន[ច�LM;ន�គយក�\��ប�Z�ប��ជន�ក�JងកមrM :ធb�ផVង;ន U7ចZ computer basketball game �3យម:នB7M�ក��ប��ច�ន

� Object-Oriented technology has many benefits:

• Ease Ease Ease Ease in software designin software designin software designin software design 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.

• Ease Ease Ease Ease in software maintenancein software maintenancein software maintenancein software maintenance: object-oriented software are easier to understand, therefore easier to test, debug, and maintain.

• Reusable Reusable Reusable Reusable softwaresoftwaresoftwaresoftware: 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.

Page 11: Java 2   chapter 10 - basic oop in java

� A class is a blueprint[ប�ង�], template[ព�ម], or prototype[

គ�� ] 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

Page 12: Java 2   chapter 10 - basic oop in java

� A class can be visualized as

a three-compartment box:

� Name

� Variables

� Methods

12

Page 13: Java 2   chapter 10 - basic oop in java

13

Page 14: Java 2   chapter 10 - basic oop in java

� The following figure shows two instances of the class Student, identified as "paul" and "perter".

14

Page 15: Java 2   chapter 10 - basic oop in java

[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.

Page 16: Java 2   chapter 10 - basic oop in java

[AccessControlModifier] type variableName [= initialValue];

16

� Example:

private double radius;

public int length = 1, width = 1;

Page 17: Java 2   chapter 10 - basic oop in java

� 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

Page 18: Java 2   chapter 10 - basic oop in java

18

Page 19: Java 2   chapter 10 - basic oop in java

� 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

Page 20: Java 2   chapter 10 - basic oop in java

� 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().

Page 21: Java 2   chapter 10 - basic oop in java

21

ប�ងv� class StudentStudentStudentStudent ន:ង class TestStudentTestStudentTestStudentTestStudent

Page 22: Java 2   chapter 10 - basic oop in java

22

ប�ងv� class SoccerPlayerSoccerPlayerSoccerPlayerSoccerPlayer ន:ង class TestSoccerPlayerTestSoccerPlayerTestSoccerPlayerTestSoccerPlayer

Page 23: Java 2   chapter 10 - basic oop in java

� 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

Page 24: Java 2   chapter 10 - basic oop in java

� 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

Page 25: Java 2   chapter 10 - basic oop in java

25

Page 26: Java 2   chapter 10 - basic oop in java

26

�គ�ថម method getArea() ���ម��

��យ�គទទ���ន�����ផ� ក"

�ប#��ង$ង��ន!

�គ�ច�' getArea()

�ប#� c1 �ន!

�ទ(ផ����ទទ���ន

ព� getArea() �ប#� c1

Page 27: Java 2   chapter 10 - basic oop in java

27

� �)ក*�ង Circle �ថម method ច�ន�នព���ទ+� ���ម��ទទ������ព� radius ន,ង color

គ- getRadius() ន,ង getColor()

� �)ក*�ង TestCircle �យ�ង�ច� ប� getRadius() ន,ង getColor() ជ�ន�#

��យ radius ន,ង color �ន / �យ�ងក0�)��ទទ���ន�ទ(ផ�� ច1*

Page 28: Java 2   chapter 10 - basic oop in java

28

2ប34*កម,ន�នផ5������

��� radius / ���4*កគ,�6

getArea() ន7ងផ5������4$�?

3នន9យ6 c1 :�ង$ង����ម,ន

�ពញ�ក<=>!

Page 29: Java 2   chapter 10 - basic oop in java

� 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

Page 30: Java 2   chapter 10 - basic oop in java

30

� �)ក*�ង Circle �យ�ង�ថម constructor

ច�ន�នប�� ច?ង� @ម

� �)ក*�ង TestCircle �យ�ង�ចប�ងA�� instance

�ប#� Circle ប��ផBងC1* �ន �Dយ� ប�

constructor ប��ផBង1*

Page 31: Java 2   chapter 10 - basic oop in java

� 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

Page 32: Java 2   chapter 10 - basic oop in java

� 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

Page 33: Java 2   chapter 10 - basic oop in java

� 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

Page 34: Java 2   chapter 10 - basic oop in java

� 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

Page 35: Java 2   chapter 10 - basic oop in java

35

Page 36: Java 2   chapter 10 - basic oop in java

36

Circle

-radius: double

-color: String

<<create>>+Circle()

<<create>>+Circle(radius: double)

<<create>>+Circle(radius: double, color: String)

+getRadius(): double

+setRadius(radius: double)

+getColor(): String

+setColor(color: String)

+getArea(): double

Page 37: Java 2   chapter 10 - basic oop in java

� 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

Page 38: Java 2   chapter 10 - basic oop in java

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

Page 39: Java 2   chapter 10 - basic oop in java

� Methods ��ងSយC�U8�ន��r `U7ច�� ន:ង�ន arguments ខJB�� �គ4ទJកZ overload method

� ច��J ច� �U8�ធ=��[យ method �U8�ន��r `U7ច�� [ចខJB�� ;នគj

� ច�ន�ន arguments

� �ប�ភទ data type G�ប�ភទ objects eបB argument ន:ម�យ]

� ច�នJច��ង��ង�8� គjZ�ផ�កeបB method’s signature � ie��ប��;B methods ��ច�ន�U8�ន��r `U7ច�� បIJ�នKខJB signatures

�� �គ�_> «overloading» 39

Page 40: Java 2   chapter 10 - basic oop in java

40

Page 41: Java 2   chapter 10 - basic oop in java

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

Page 42: Java 2   chapter 10 - basic oop in java

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

Page 43: Java 2   chapter 10 - basic oop in java

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

Page 44: Java 2   chapter 10 - basic oop in java

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

Page 45: Java 2   chapter 10 - basic oop in java

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

Page 46: Java 2   chapter 10 - basic oop in java

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

Page 47: Java 2   chapter 10 - basic oop in java

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 Now, a box is built

by a method on

line 25 47

Page 48: Java 2   chapter 10 - basic oop in java

� 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

Page 49: Java 2   chapter 10 - basic oop in java

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

Page 50: Java 2   chapter 10 - basic oop in java

� For reusable code : For reusable code : For reusable code : For reusable code : If you need to do the same thing, or almost the same thing, many times, write a method to do it, then call the method each time you have to do that task. � �បB:ន�ប� ��កចង�[យកមrM :ធb�ធ=�ie�eU7ច�� ��ច�នUង ច7eប�ងv� method ម�យ e�ច�g�យ

�_kមក��ប� p8�ព8��ក�LMie�[យk�ធ=�ie�e��ង�f`

� To parameterize code : To parameterize code : To parameterize code : To parameterize code : 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��ប��;B;I pI �មI� �U�ម�b�� BបK7eM :ធb�ធ=�ieeបB method

50

Page 51: Java 2   chapter 10 - basic oop in java

51

� For topFor topFor topFor top----down programming : down programming : down programming : down programming : A very useful style of programming is called top-down 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 � ប�ងv� method B�pប�3`��យប�� ធ��[យ�\Zប�� 7ច]

� To create conceptual units : To create conceptual units : To create conceptual units : To create conceptual units : 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 ម�យ B�pប�3`��យប�� �ម�យគ 9 k�យ�B�8�ធ=�ieZម�យកមrM :ធb

��ងម78

Page 52: Java 2   chapter 10 - basic oop in java

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�ព��មប�ងv�eបBថrb �ប�[ច�\e�ច ច7e��ប� class ន:ង method �U8�ន��ប eបB Java API 9 kiបនyយ�ព8�M� ន:ង�ច^Bkងក�gJB;ន��ច�ន9

2. �U�ម�b�8�កក�ពB8ទ ¡ព��ប��;B� �ងM :ញeបBកមrM :ធb method ន:ម�យ]គ�e��នJMKie�e�ម�យ �g�យ��r `eបB method គ�e�B��Uង�[យ�នន¢យច��a`ie�e�f` 9 k�យ�B�8Be�Be �B=ងeកក�gJB �ថeកs ន:ង�កeB�e�89

3. �គប method 7ច]��ង�B�U8�នJMKie�e�ម�យ �យ�ក8�ង ន:ងeកក�gJBZង method ធ� �U8�ធ=�ie�e��ច�ន9

52

Page 53: Java 2   chapter 10 - basic oop in java

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 Math Math Math Math Z�ផ�កម�យ¥ន java.langjava.langjava.langjava.lang package �U8�LM;ន import �3យB=¢យ�បMK: 9 U7�ច�̀ ��កម:ន4�;ច�LMie import java.util.Math �ទ^�ទ

5. Method �U8បK7e�¥8eបB private

variable គ�e�ច§B> �¥8ថrb�f` Z�¥8�Oម�LM �ប�ម:នU7�4� `�ទ គ�e��ប� setXXX method 9

6. Online Java API Documentation �ន¡ព�យ�B�8ក�Jងie�B=ងeកពT¢�ន8��:eបB class 9 �@�ព8��ក;ន�e^ន��ពb class Cម�យ គ�e�នទ��ប�B=ងeក�ម�8ពT¢�នប�នyម��ពb class �f` �@ក�Jង Java API Doc.

53

Page 54: Java 2   chapter 10 - basic oop in java

� 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

Page 55: Java 2   chapter 10 - basic oop in java

� 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

Page 56: Java 2   chapter 10 - basic oop in java

� 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

Page 57: Java 2   chapter 10 - basic oop in java

� 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

Page 58: Java 2   chapter 10 - basic oop in java

� Write the Author

class. Also write a

test program called

TestAuthor to test

the constructor and

public methods.

58

Try changing the email of an author, e.g

Author anAuthor = new Author("Tan Ah Teck", "[email protected]", 'm');

System.out.println(anAuthor); // call toString()

anAuthor.setEmail("[email protected]")

System.out.println(anAuthor);

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

Page 59: Java 2   chapter 10 - basic oop in java

59

� Write the class Book (which uses the Author class written earlier). Also write a test program called

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);

AuthorBook

-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

Page 60: Java 2   chapter 10 - basic oop in java

� 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

Page 61: Java 2   chapter 10 - basic oop in java

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]);

}

Page 62: Java 2   chapter 10 - basic oop in java

� Write the MyCircle class. Also write a test program (called

TestMyCircle) to test all the methods defined in the class.

62

Page 63: Java 2   chapter 10 - basic oop in java

� Write the MyTriangle class. Also write a test

program (called TestMyTriangle) to test all the

methods defined in the class.

63

Page 64: Java 2   chapter 10 - basic oop in java

64

Page 65: Java 2   chapter 10 - basic oop in java

65

Page 66: Java 2   chapter 10 - basic oop in java

� ច7eប�ងv� class ម�យ��r ` Invoice �U8�កªមg«Jន8ក Hardware ��ប�B�pបie8កទ�ន:ញ¬ a) Invoice គ�e�នព­�នច�ន�ន ® U7ចZ �8ខក7Uទ�ន:ញ (part number: String) ie

បe :�យ (part description: String) ច�ន�ន¯កl8ក (quantity: int) ន:ង�¥8¯កl (unit price: double) 9

b) Class �ន`គ�e�ន constructor ម�យB�pប initialize instance variable ��ង ® �ង�8� c) ប�ងv� set ន:ង get method B�pប instance variables ន:ម�យ] d) ប�ងv� method ម�យ��r ` getInvoiceAmount B�pបគ�f�¥8BeJបក�Jង Invoice

e�ច�g�យ return �¥8Z double e) ប�ងv� method ម�យ��r ` printInvoice �U�ម�bប�� ញព­�ន8��:�@�8� Invoice 9

�បB:ន�ប� quantity ម:ន�មនZច�ន�នM :ជ±�ន �LMក���[យk�ន�¥8 0 9 �បB:ន�ប� �¥8pយ ម:ន�មនZច�ន�នM :ជ±�ន �LMក���[យk�ន�¥8 0.0 9

f) ប�ងv�កមrM :ធbម�យ��r ` InvoiceTest B�pប�ក8�ង��ប� Invoice 9 66

Page 67: Java 2   chapter 10 - basic oop in java

Invoice

-partNumber: String-partDescription: String-quantity: int-unitPrice: double

<<create>>+Invoice(partNumber: String, partDescription: String, quantity: int, unitPrice: double)+setPartNumber(partNumber: String)+setPartDescription(partDescription: String)+setQuantity(quantity: int)+setUnitPrice(unitPrice: double)+getPartNumber(): String+getPartDescription(): String+getQuantity(): int+getUnitPrice(): double+getInvoiceAmount(): double+printInvoice()

67

Page 68: Java 2   chapter 10 - basic oop in java

Employee

-firstName: String-lastName: String-monthlySalary: float

<<create>>+Employee(firstName: String, lastName: String, monthlySalary: float)+setFirstName(firstName: String): void+setLastName(lastName: String): void+setMonthlySalary(monthlySalary: float): void+getFirstName(): String+getLastName(): String+getMonthlySalary(): float+getYearlySalary(): float

� ច7eប�ងv� class ម�យ��r ` Employee �U8�នព­�នច�ន�ន ³ Z instance variable U7ចZ first name, last name ន:ង monthly salary 9 � ប�ងv� constructor ម�យB�pប initialize instance variable ��ង ³ � ប�ងv� set ន:ង get method B�pប instance variable ន:ម�យ] 9

�បB:ន�ប� monthly salary ម:ន�មនZច�ន�នM :ជ±�ន �LM�[យk�Br� n 9 � ប�ងv�កមrM :ធbម�យ��r ` EmployeeTest B�pប��ប� Employee �3យប�ងv�

Employee object ច�ន�ន 2 e�ច�g�យប�� ញ yearly salary eបB object ន:ម�យ] 9 ចJងប56ប�� �ង�;ក�ខច�ន�ន 10% ន:ងប�� ញ yearly salary �eZថrbមKង�ទ^9

68