CLASS AND OBJECTS Valerie Chu, Ph.D. LeMoyne-Owen College 1
Existing Data Types Declare a variable: 2 LeMoyne-Owen College
Create your own data type 3 LeMoyne-Owen College
Class & Objects Class – blueprint e.g., Course Object – house e.g., JAVAI, JAVAII, Data Structures,…etc. Characteristic of an object Instructor, number of seats,…etc. Behavior Change instructor, increase number of seats,…etc. LeMoyne-Owen College 4
5
Class & Objects (cont.) Characteristic – Instance Variable A storage – not take any action, no (). private – only methods within the same class can view or change it. Data is protected. – encapsulation. data type – to know how large of storage to be reserved. variable name – no space (one word only) e.g., numOfStudents. LeMoyne-Owen College 6
Class & Objects (cont.) Behavior – Method or Constructor Take an action – () is needed. public – client (main method) can call it. Interface between client and methods. return data type – what type information the method return to caller? void - no return information. parameter – information needed from caller. - Can be only used within the block of the method, it located. - data type is needed. LeMoyne-Owen College 7
Constructor A special method Take an action : Constructor’s job: Initialize objects; i.e. initialize instance variables. Be called when a new object of the class is declared. Has the same name as the class name. No return data type. Number of parameters usually, not always, is same as number of instance variables. public LeMoyne-Owen College 8
Declare a class 9 LeMoyne-Owen College
10 LeMoyne-Owen College
11 LeMoyne-Owen College
12 LeMoyne-Owen College
Default constructor If a programmer did not set any constructor, the Java compiler has a default constructor with no parameters. Set zero for primitive number types. Set false for boolean values Set null for references (e.g. String type) 13 LeMoyne-Owen College
Example 14 LeMoyne-Owen College
What if a constructor is set? 15 LeMoyne-Owen College
16 LeMoyne-Owen College
What if a constructor is set? (cont.) 17 LeMoyne-Owen College
What if a constructor is set?(Cont.) A constructor is created in a class. Default constructor is turned off. The no-argument constructor is required if a client creates an object with no initial values. Constructor Overload 18 LeMoyne-Owen College
19 Constructor Overload LeMoyne-Owen College
20 LeMoyne-Owen College
21 LeMoyne-Owen College
22 LeMoyne-Owen College
23 LeMoyne-Owen College
Compile and run javac *.java java CourseTest 24 LeMoyne-Owen College
Compare two objects 25 LeMoyne-Owen College