SlideShare ist ein Scribd-Unternehmen logo
1 von 68
Downloaden Sie, um offline zu lesen
Lecture d by: CHEA VICHET 
077 657 007 
1
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
បកចង
ង PC មយ
គង 
កន	
យក motherboard, 
processor, RAMs, hard disk, 
casing, power supply មក3ក	 
4បប	5768 9 កមន:4;ច	 
ខ=8
RAM ផ8:
@ប
ទB 
C Hard Disk ធG
7ច
ទ! បJIនK 
ក4;ច	
LMន interface 
Oម 

LM 9
បកនIDE Hard Disk 
ក
LM
ន motherboard 
support IDE. 
3
4 
 SនកT
LM;នU
ងផVផJ
W3យ
គង (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ផJ
W
ង
3យ
គង U8
គ
_ reusable components.
5 
 ចJ`ច
a` software Mញb? ក[ច
ធ =software application 
មយ
3យ
eBយក routine
ន`
eយBយក routine
f` eច
gយeពOង program U
នeie;ន
ទ? 
 ច
8គj
ទ! មន:U7ច hardware
ទ! kZie8;កCB	 កJង 
ieផVផJ Wapplication មយ
3យ software components 9 
 4ប	lងពb mn oមJន
គBe
Be programs
ចនpប	ម:នB	! 
គប 	application ថbនr:មយ]
គ
LMB:កsB=ងeក eច
gយBe
BeកមMrធ:b4បព	bចនJចB7នtមក
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
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
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.
9 
 បកចង	Be
Be soccer games មយ 9 ក 
នOងជបie8;កកJងieប
ង
v game កJង 
procedural languages 9 បJIនK OOP languages, 
[ច
[យកប
ង
vកមrMធ:b
3យពOងផxក
8M
Jពy:
] 
U8នកJង soccer games. 
 Player: 
▪ Attributes: name, number, location 
▪ Operations: run, jump, kick-the-ball 
 Ball: 
 Reference: 
 Field: 
 Audience: 
 Weather:
Classes មយចនន[ច
LM;ន
គយក
បZប
€ជនកJងកមMrធ:b
ផVង;ន U7ច 
Z computer basketball game
3យម:នB7Mកប
ចន 
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.
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
A class can be visualized as 
a three-compartment box: 
 Name 
 Variables 
 Methods 
12
13
The following figure shows two instances of the 
class Student, identified as paul and perter. 
14
[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.

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Java Programming - Polymorphism
Java Programming - PolymorphismJava Programming - Polymorphism
Java Programming - Polymorphism
 
04. Review OOP with Java
04. Review OOP with Java04. Review OOP with Java
04. Review OOP with Java
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4
 
Introduction to c ++ part -2
Introduction to c ++   part -2Introduction to c ++   part -2
Introduction to c ++ part -2
 
Basic c#
Basic c#Basic c#
Basic c#
 
Javapolymorphism
JavapolymorphismJavapolymorphism
Javapolymorphism
 
‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
 
Seminar on java
Seminar on javaSeminar on java
Seminar on java
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
Testing for share
Testing for share Testing for share
Testing for share
 
Inheritance and polymorphism
Inheritance and polymorphism   Inheritance and polymorphism
Inheritance and polymorphism
 
‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism
 
C# programming
C# programming C# programming
C# programming
 
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
20170113 julia’s type system and multiple dispatch
20170113 julia’s type system and multiple dispatch20170113 julia’s type system and multiple dispatch
20170113 julia’s type system and multiple dispatch
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Java Programming - Introduction to Abstract Class
Java Programming - Introduction to Abstract ClassJava Programming - Introduction to Abstract Class
Java Programming - Introduction to Abstract Class
 
JAVA Polymorphism
JAVA PolymorphismJAVA Polymorphism
JAVA Polymorphism
 

Ähnlich wie Java 2 chapter 10 - basic oop in java

Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov
 
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
quantumiq448
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
Connex
 

Ähnlich wie Java 2 chapter 10 - basic oop in java (20)

OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
Objective c slide I
Objective c slide IObjective c slide I
Objective c slide I
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5
 
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
JavaBasicsCore1.ppt
JavaBasicsCore1.pptJavaBasicsCore1.ppt
JavaBasicsCore1.ppt
 
slides 01.ppt
slides 01.pptslides 01.ppt
slides 01.ppt
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
 
Bt0065, c programming and data structures
Bt0065, c programming and data structuresBt0065, c programming and data structures
Bt0065, c programming and data structures
 
Java02
Java02Java02
Java02
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java generics final
Java generics finalJava generics final
Java generics final
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
09slide.ppt
09slide.ppt09slide.ppt
09slide.ppt
 
09slide.ppt oops classes and objects concept
09slide.ppt oops classes and objects concept09slide.ppt oops classes and objects concept
09slide.ppt oops classes and objects concept
 

Mehr von let's go to study

009 sql server management studio
009 sql server management studio009 sql server management studio
009 sql server management studio
let's go to study
 

Mehr von let's go to study (20)

Rs instructor ppt_chapter11_final
Rs instructor ppt_chapter11_finalRs instructor ppt_chapter11_final
Rs instructor ppt_chapter11_final
 
Ch10
Ch10Ch10
Ch10
 
Before beginning
Before beginningBefore beginning
Before beginning
 
Chapter 8 (security)
Chapter 8 (security)Chapter 8 (security)
Chapter 8 (security)
 
Chapter 7 (ado.net)
Chapter 7 (ado.net)Chapter 7 (ado.net)
Chapter 7 (ado.net)
 
Chapter 6 (data binding)
Chapter 6 (data binding)Chapter 6 (data binding)
Chapter 6 (data binding)
 
Chapter 5 (master page)
Chapter 5 (master page)Chapter 5 (master page)
Chapter 5 (master page)
 
Chapter 4 (navigater)
Chapter 4 (navigater)Chapter 4 (navigater)
Chapter 4 (navigater)
 
Chapter 3 (validation control)
Chapter 3 (validation control)Chapter 3 (validation control)
Chapter 3 (validation control)
 
Chapter 2 (web servercontrol)
Chapter 2 (web servercontrol)Chapter 2 (web servercontrol)
Chapter 2 (web servercontrol)
 
Chapter 1 (asp.net over view)
Chapter 1 (asp.net over view)Chapter 1 (asp.net over view)
Chapter 1 (asp.net over view)
 
Before beginning
Before beginningBefore beginning
Before beginning
 
Sadchap04
Sadchap04Sadchap04
Sadchap04
 
Sadchap03
Sadchap03Sadchap03
Sadchap03
 
Sadchap02
Sadchap02Sadchap02
Sadchap02
 
Sadchap01
Sadchap01Sadchap01
Sadchap01
 
database design process
database design processdatabase design process
database design process
 
009 sql server management studio
009 sql server management studio009 sql server management studio
009 sql server management studio
 
007 sql server-installation
007 sql server-installation007 sql server-installation
007 sql server-installation
 
Chapter 2-html-tage
Chapter 2-html-tageChapter 2-html-tage
Chapter 2-html-tage
 

Java 2 chapter 10 - basic oop in java

  • 1. Lecture d by: CHEA VICHET 077 657 007 1
  • 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
  • 5. គង កន យក motherboard, processor, RAMs, hard disk, casing, power supply មក3ក 4បប 5768 9 កមន:4;ច ខ=8
  • 8. ទB C Hard Disk ធG 7ច
  • 9. ទ! បJIនK ក4;ច LMន interface Oម LM 9
  • 10. បកនIDE Hard Disk ក LM ន motherboard support IDE. 3
  • 13. W3យ
  • 15. ចនU7ចZ chasis, doors, engine, wheels, break, transmission, etc. Components
  • 16. គ4 ទJក reusable, e.g., wheel [ចយក
  • 19. ទ^ ;ន Hardware U7ចZ computers ន:ង cars LM;នផVផJ
  • 20. W ង
  • 21. 3យ
  • 23.
  • 28. 3យ
  • 30. ន`
  • 36. 8គj
  • 38. ទ! kZie8;កCB កJង ieផVផJ Wapplication មយ
  • 39. 3យ software components 9 4ប lងពb mn oមJន
  • 40. គBe
  • 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.
  • 50. Be soccer games មយ 9 ក នOងជបie8;កកJងieប
  • 51. ង v game កJង procedural languages 9 បJIនK OOP languages, [ច
  • 55. 8M Jពy: ] U8នកJង soccer games. Player: ▪ Attributes: name, number, location ▪ Operations: run, jump, kick-the-ball Ball: Reference: Field: Audience: Weather:
  • 60. ផVង;ន U7ច Z computer basketball game
  • 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
  • 66. 13
  • 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.
  • 69. [AccessControlModifier] type variableName [= initialValue]; 16 Example: private double radius; public int length = 1, width = 1;
  • 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
  • 71. 18
  • 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().
  • 75. ងv class SSSSttttuuuuddddeeeennnntttt ន:ង class TTTTeeeessssttttSSSSttttuuuuddddeeeennnntttt
  • 77. ងv class SSSSoooocccccccceeeerrrrPPPPllllaaaayyyyeeeerrrr ន:ង class TTTTeeeessssttttSSSSoooocccccccceeeerrrrPPPPllllaaaayyyyeeeerrrr
  • 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
  • 80. 25
  • 81. 26 គថម method getArea() ម យគទទនផ ក
  • 82. ប#
  • 84. ប# c1 ន! ទ(ផទទន ព getArea()
  • 86. )ក*ង Circle ថម method ចននព
  • 87. ទ+ មទទព radius ន,ង color គ- getRadius() ន,ង getColor() 27 )ក*ង TestCircle យងច ប getRadius() ន,ង getColor() ជន# យ radius ន,ង color ន / យងក0)ទទនទ(ផ ច1*
  • 88. 28 2ប34*កម,ននផ5 radius / 4*កគ,6 getArea() ន7ងផ54?$ 3នន9យ6 c1 :
  • 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
  • 91. 30 )ក*ង Circle យងថម constructor ចននប ច?ង @ម )ក*ង TestCircle យងចបងA instance
  • 92. ប# Circle បផBងC1*ន Dយ ប constructor បផBង1*
  • 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
  • 97. 35
  • 98. 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
  • 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
  • 103. គ4 ទJកZ overload method ចŠJច‹ U8
  • 104.
  • 106. ‰r`U7ច [ចខJB;នគj ចនន arguments ប
  • 108. ភទ objects eបB argument ន:មយ] ចនJចˆង‹ង
  • 113.
  • 115. 40
  • 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
  • 125. FFFFoooorrrr rrrreeeeuuuussssaaaabbbblllleeee ccccooooddddeeee :::: 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:ន
  • 131. gយ
  • 133. ប p8
  • 135. [យk
  • 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 ប
  • 144. [យ
  • 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ពœ€មប
  • 152. ប class ន:ង method U8ន—ប eបB Java API 9 ki បនyយ
  • 153. ព8
  • 159. ប;B
  • 160. ងMញ: eបB កមMrធ:b method ន:មយ]គe នJM K ie‘e មយ
  • 161. gយ
  • 166. Be B=ងeកកgJB ថ eកs ន:ងកeBe89 3. គប method 7ច]ˆងB U8នJM K ie‘e មយ ‘យ—ក8“ង ន:ងeកកgJB Zង method ធ U8
  • 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
  • 172. ទ^
  • 173. ទ 5. Method U8ប7eK ¥8eបB private variable គe ច§B ¥8ថb
  • 176. 4`
  • 178. ប setXXX method 9 6. Online Java API Documentation ន ¡ព‘យB8šកJងieBង=eកព T¢ន8: eបB class 9
  • 179. @
  • 181. e^នពb class Cមយ គeនទžប B=ងeក
  • 183. f`
  • 184. @កJង Java API Doc. 53
  • 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
  • 195. 64
  • 196. 65
  • 200. បBpប ie8ក ទន:ញ¬ a) Invoice គeនព ­នចនន ® U7ចZ
  • 201. 8ខក7Uទន:ញ (part number: String) ie បe€:យ (part description: String) ចនន¯កl8ក (quantity: int) ន:ង ¥8¯កl (unit price: double) 9 b) Class
  • 202. ន`គeន constructor មយBpប initialize instance variable ˆង ® ង
  • 204. ងv set ន:ង get method Bpប instance variables ន:មយ] d) ប
  • 207. gយ return ¥8Z double e) ប
  • 211. @
  • 212. 8 Invoice 9 បB:ន
  • 214. [យkន ¥8 0 9 បB:ន
  • 220. 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
  • 221. 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ប
  • 223. ‰r` Employee U8នព ­នចនន ³ Z instance variable U7ចZ first name, last name ន:ង monthly salary 9 ប
  • 224. ង v constructor មយBpប initialize instance variable ˆង ³ ប
  • 225. ង v set ន:ង get method Bpប instance variable ន:មយ] 9 បB:ន
  • 226. ប monthly salary មន:មនZចននMជ:±ន LM
  • 227. [យk
  • 228. B rn 9
  • 233. ង v Employee object ចនន 2 eច
  • 234. gយប‘™ញ yearly salary eបB object ន: មយ] 9 ចJងប56ប
  • 235. ង;ក ខចនន 10% ន:ងប‘™ញ yearly salary —eZថbមrងK