下載本文檔
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、1,Chapter 8 Objects and Classes,2,Motivations,After learning the preceding chapters, you are capable of solving many programming problems using selections, loops, methods, and arrays. However, these Java features are not sufficient for developing graphical user interfaces and large scale software sy
2、stems. Suppose you want to develop a graphical user interface as shown below. How do you program it?,3,Objectives,To describe objects and classes, and use classes to model objects (8.2). To use UML graphical notations to describe classes and objects (8.2). To demonstrate defining classes and creatin
3、g objects (8.3). To create objects using constructors (8.4). To access objects via object reference variables (8.5). To define a reference variable using a reference type (8.5.1). To access an objects data and methods using the object member access operator (.) (8.5.2). To define data fields of refe
4、rence types and assign default values for an objects data fields (8.5.3). To distinguish between object reference variables and primitive data type variables (8.5.4). To use classes Date, Random, and JFrame in the Java library (8.6). To distinguish between instance and static variables and methods (
5、8.7). To define private data fields with appropriate get and set methods (8.8). To encapsulate data fields to make classes easy to maintain (8.9). To develop methods with object arguments and differentiate between primitive-type arguments and object-type arguments (8.10). To store and process object
6、s in arrays (8.11).,4,OO Programming Concepts,Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that can be distinctly identified. For example, a student, a desk, a circle, a button, and even a loan can all be viewed as objects. An
7、 object has a unique identity, state, and behaviors. The state of an object consists of a set of data fields (also known as properties) with their current values. The behavior of an object is defined by a set of methods.,5,Objects,An object has both a state and behavior. The state defines the object
8、, and the behavior defines what the object does.,6,Classes,Classes are constructs that define objects of the same type. A Java class uses variables to define data fields and methods to define behaviors. Additionally, a class provides a special type of methods, known as constructors, which are invoke
9、d to construct objects from the class.,7,Classes,8,UML Class Diagram,9,Example: Defining Classes and Creating Objects,Objective: Demonstrate creating objects, accessing data, and using methods.,TestCircle1,Run,10,Example: Defining Classes and Creating Objects,Objective: Demonstrate creating objects,
10、 accessing data, and using methods.,TestTV,Run,TV,11,Constructors,Circle() Circle(double newRadius) radius = newRadius; ,Constructors are a special kind of methods that are invoked to construct objects.,12,Constructors, cont.,A constructor with no parameters is referred to as a no-arg constructor. C
11、onstructors must have the same name as the class itself. Constructors do not have a return typenot even void. Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects.,13,Creating Objects Using Constructors,new ClassName(); Example
12、: new Circle(); new Circle(5.0);,14,Default Constructor,A class may be declared without constructors. In this case, a no-arg constructor with an empty body is implicitly declared in the class. This constructor, called a default constructor, is provided automatically only if no constructors are expli
13、citly declared in the class.,15,Declaring Object Reference Variables,To reference an object, assign the object to a reference variable. To declare a reference variable, use the syntax: ClassName objectRefVar; Example: Circle myCircle;,16,Declaring/Creating Objectsin a Single Step,ClassName objectRef
14、Var = new ClassName(); Example: Circle myCircle = new Circle();,Create an object,Assign object reference,17,Accessing Objects,Referencing the objects data: objectRefVar.data e.g., myCircle.radius Invoking the objects method: objectRefVar.methodName(arguments) e.g., myCircle.getArea(),18,Trace Code,C
15、ircle myCircle = new Circle(5.0); SCircle yourCircle = new Circle(); yourCircle.radius = 100;,Declare myCircle,no value,myCircle,animation,19,Trace Code, cont.,Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100;,no value,myCircle,Create a circle,animation,20
16、,Trace Code, cont.,Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100;,reference value,myCircle,Assign object reference to myCircle,animation,21,Trace Code, cont.,Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100;,r
17、eference value,myCircle,no value,yourCircle,Declare yourCircle,animation,22,Trace Code, cont.,Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100;,reference value,myCircle,no value,yourCircle,Create a new Circle object,animation,23,Trace Code, cont.,Circle my
18、Circle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100;,reference value,myCircle,reference value,yourCircle,Assign object reference to yourCircle,animation,24,Trace Code, cont.,Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100;,
19、reference value,myCircle,reference value,yourCircle,Change radius in yourCircle,animation,25,Caution,Recall that you use Math.methodName(arguments) (e.g., Math.pow(3, 2.5) to invoke a method in the Math class. Can you invoke getArea() using Circle1.getArea()? The answer is no. All the methods used b
20、efore this chapter are static methods, which are defined using the static keyword. However, getArea() is non-static. It must be invoked from an object using objectRefVar.methodName(arguments) (e.g., myCircle.getArea(). More explanations will be given in the section on “Static Variables, Constants, a
21、nd Methods.”,26,Reference Data Fields,The data fields can be of reference types. For example, the following Student class contains a data field name of the String type.,public class Student String name; / name has default value null int age; / age has default value 0 boolean isScienceMajor; / isScie
22、nceMajor has default value false char gender; / c has default value u0000 ,27,The null Value,If a data field of a reference type does not reference any object, the data field holds a special literal value, null.,28,Default Value for a Data Field,The default value of a data field is null for a refere
23、nce type, 0 for a numeric type, false for a boolean type, and u0000 for a char type. However, Java assigns no default value to a local variable inside a method.,public class Test public static void main(String args) Student student = new Student(); System.out.println(name? + ); System.ou
24、t.println(age? + student.age); System.out.println(isScienceMajor? + student.isScienceMajor); System.out.println(gender? + student.gender); ,29,Example,public class Test public static void main(String args) int x; / x has no default value String y; / y has no default value System.out.println(x is + x
25、); System.out.println(y is + y); ,Compilation error: variables not initialized,Java assigns no default value to a local variable inside a method.,30,Differences between Variables of Primitive Data Types and Object Types,31,Copying Variables of Primitive Data Types and Object Types,32,Garbage Collect
26、ion,As shown in the previous figure, after the assignment statement c1 = c2, c1 points to the same object referenced by c2. The object previously referenced by c1 is no longer referenced. This object is known as garbage. Garbage is automatically collected by JVM.,33,Garbage Collection, cont,TIP: If
27、you know that an object is no longer needed, you can explicitly assign null to a reference variable for the object. The JVM will automatically collect the space if the object is not referenced by any variable.,34,The Date Class,Java provides a system-independent encapsulation of date and time in the
28、 java.util.Date class. You can use the Date class to create an instance for the current date and time and use its toString method to return the date and time as a string.,35,The Date Class Example,For example, the following code java.util.Date date = new java.util.Date(); System.out.println(date.toS
29、tring(); displays a string like Sun Mar 09 13:50:19 EST 2003.,36,The Random Class,You have used Math.random() to obtain a random double value between 0.0 and 1.0 (excluding 1.0). A more useful random number generator is provided in the java.util.Random class.,37,The Random Class Example,If two Rando
30、m objects have the same seed, they will generate identical sequences of numbers. For example, the following code creates two Random objects with the same seed 3.,Random random1 = new Random(3); System.out.print(From random1: ); for (int i = 0; i 10; i+) System.out.print(random1.nextInt(1000) + ); Ra
31、ndom random2 = new Random(3); System.out.print(nFrom random2: ); for (int i = 0; i 10; i+) System.out.print(random2.nextInt(1000) + );,From random1: 734 660 210 581 128 202 549 564 459 961 From random2: 734 660 210 581 128 202 549 564 459 961,38,Displaying GUI Components,When you develop programs to
32、 create graphical user interfaces, you will use Java classes such as JFrame, JButton, JRadioButton, JComboBox, and JList to create frames, buttons, radio buttons, combo boxes, lists, and so on. Here is an example that creates two windows using the JFrame class.,TestFrame,Run,39,Trace Code,JFrame fra
33、me1 = new JFrame(); frame1.setTitle(Window 1); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle(Window 2); frame2.setSize(200, 150); frame2.setVisible(true);,Declare, create, and assign in one statement,reference,frame1,: JFrame title: width: height: v
34、isible:,animation,40,Trace Code,JFrame frame1 = new JFrame(); frame1.setTitle(Window 1); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle(Window 2); frame2.setSize(200, 150); frame2.setVisible(true);,reference,frame1,: JFrame title: Window 1 width: hei
35、ght: visible:,Set title property,animation,41,Trace Code,JFrame frame1 = new JFrame(); frame1.setTitle(Window 1); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle(Window 2); frame2.setSize(200, 150); frame2.setVisible(true);,reference,frame1,: JFrame t
36、itle: Window 1 width: 200 height: 150 visible:,Set size property,animation,42,Trace Code,JFrame frame1 = new JFrame(); frame1.setTitle(Window 1); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle(Window 2); frame2.setSize(200, 150); frame2.setVisible(tr
37、ue);,reference,frame1,: JFrame title: Window 1 width: 200 height: 150 visible: true,Set visible property,animation,43,Trace Code,JFrame frame1 = new JFrame(); frame1.setTitle(Window 1); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle(Window 2); frame2
38、.setSize(200, 150); frame2.setVisible(true);,reference,frame1,: JFrame title: Window 1 width: 200 height: 150 visible: true,Declare, create, and assign in one statement,reference,frame2,: JFrame title: width: height: visible:,animation,44,Trace Code,JFrame frame1 = new JFrame(); frame1.setTitle(Wind
39、ow 1); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle(Window 2); frame2.setSize(200, 150); frame2.setVisible(true);,reference,frame1,: JFrame title: Window 1 width: 200 height: 150 visible: true,reference,frame2,: JFrame title: Window 2 width: height
40、: visible:,Set title property,animation,45,Trace Code,JFrame frame1 = new JFrame(); frame1.setTitle(Window 1); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle(Window 2); frame2.setSize(200, 150); frame2.setVisible(true);,reference,frame1,: JFrame titl
41、e: Window 1 width: 200 height: 150 visible: true,reference,frame2,: JFrame title: Window 2 width: 200 height: 150 visible:,Set size property,animation,46,Trace Code,JFrame frame1 = new JFrame(); frame1.setTitle(Window 1); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(
42、); frame2.setTitle(Window 2); frame2.setSize(200, 150); frame2.setVisible(true);,reference,frame1,: JFrame title: Window 1 width: 200 height: 150 visible: true,reference,frame2,: JFrame title: Window 2 width: 200 height: 150 visible: true,Set visible property,animation,47,Adding GUI Components to Wi
43、ndow,You can add graphical user interface components, such as buttons, labels, text fields, combo boxes, lists, and menus, to the window. The components are defined using classes. Here is an example to create buttons, labels, text fields, check boxes, radio buttons, and combo boxes.,GUIComponents,Ru
44、n,48,Instance Variables, and Methods,Instance variables belong to a specific instance.Instance methods are invoked by an instance of the class.,49,Static Variables, Constants, and Methods,Static variables are shared by all the instances of the class.Static methods are not tied to a specific object.
45、Static constants are final variables shared by all the instances of the class.,50,Static Variables, Constants, and Methods, cont.,To declare static variables, constants, and methods, use the static modifier.,51,Static Variables, Constants, and Methods, cont.,52,Example ofUsing Instance and Class Variables and Method,Objective: Demonstrate the roles of instance and class variables and their uses. This example adds a class variable numberOfObjects to track the number of Circle objects created.,TestCircle2,Run,Circle2,53,Visibi
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 技偵執(zhí)法考試試題及答案
- 2026四川綿陽市三臺(tái)縣公安局招聘警務(wù)輔助人員60人參考考試試題附答案解析
- 2026年煙臺(tái)海陽市事業(yè)單位公開招聘工作人員(35人)備考考試題庫(kù)附答案解析
- 2026北京急救中心第一批招聘2人參考考試題庫(kù)附答案解析
- 2026云南玉溪市澄江市綜合行政執(zhí)法局招聘執(zhí)法輔助人員招聘1人備考考試題庫(kù)附答案解析
- 2026年上半年黑龍江事業(yè)單位聯(lián)考省人民政府黑瞎子島建設(shè)和管理委員會(huì)招聘4人備考考試題庫(kù)附答案解析
- 2026上半年云南事業(yè)單位聯(lián)考省水利廳部分直屬事業(yè)單位公開招聘人員參考考試試題附答案解析
- 2026鷹潭月湖恒通村鎮(zhèn)銀行春季員工招聘參考考試試題附答案解析
- 揭陽警察面試題目及答案
- 文職輔警筆試題庫(kù)及答案
- 新版預(yù)算管理制度
- 冬季道路施工應(yīng)對(duì)措施
- 云南省昆明市官渡區(qū)2024-2025學(xué)年九年級(jí)上學(xué)期期末學(xué)業(yè)質(zhì)量監(jiān)測(cè)英語試題(含答案)
- 企業(yè)員工培訓(xùn)分層方案
- 體檢中心新員工培訓(xùn)教材
- 衛(wèi)生院綜合樓施工組織設(shè)計(jì)
- 淮安市2022-2023學(xué)年七年級(jí)上學(xué)期期末歷史試題【帶答案】
- 腦動(dòng)脈供血不足的護(hù)理查房
- 《中醫(yī)藥健康知識(shí)講座》課件
- 中國(guó)地級(jí)市及各省份-可編輯標(biāo)色地圖
- 急性消化道出血的急診處理
評(píng)論
0/150
提交評(píng)論