Creating Objects &
Implementing Methods
Coding with
CREATING OBJECT
• To use classes in a program, we need to create an object from
the class.
• Two steps to create an object:
- STEP 1: Declaration – declare object reference variable
- STEP 2: Object instantiation – create an object
CREATING OBJECT: STEP 1 - DECLARATION
• Syntax to declare object reference variable:
<ObjectType> <objectName>;
where:
- <ObjectType> – the type of object (a class name).
- <objectName> – the name of object reference variable.
DECLARING OBJECT REFERENCE VARIABLES
• To create an object, you must declare a reference variable of the object class type.
• The reference variable will store the address (reference) of the object in memory.
• Note: A variable holds either a primitive type or a reference to an object
• A class name is used as a type to declare an object reference variable, e.g.:
Student stud;
• No object is created with this declaration
• An object reference variable holds the address of an object
• The object itself must be created separately
CREATING OBJECTS
• Generally, we use the new operator to create an object
stud = new Student ("Ali","s1111");
This calls the Student constructor, which is
a special method that sets up the object
• Creating an object is called instantiation
• An object is an instance of a particular class
TYPES OF VARIABLES IN JAVA: PRIMITIVE TYPE &
REFERENCE VARIABLES
A variable can be either a primitive type or a reference variable.
Numerical data are called primitive data types. (int, float, double, etc).
A primitive variable contains the value itself.
Objects are called reference data types (or ‘object reference variable),
because the contents of the variable are the addresses that refer to
memory locations where the objects are actually stored (can be
thought of as a pointer to the location of the object).
Java variables
Primitive type Reference
variables variables
Example: Example:
int x; Student student1;
x = 45; student1 = new Student("Ali","s1111");
Variable student1 stores memory location (1234), that is
x 45 the address of the memory space where actual data is
stored.
Variable x and an int value in
its memory space
student1 1234 Object student1
reference variable 1234 student1 :Student
name = “Ali”
matricNo = “s1111”
MEMORY STATUS WHEN DECLARING & CREATING OBJECT
1234
student1 :Student
1234
RECAP: UML CLASS DIAGRAM
Student Class Name
-studName: String
-matricNumber: String Attributes
-marks: double
+ Student(String name, String matric)
+ setMarks(double studentMarks):void Methods
+ determineGrade () : String
+ displayInfo() : void
UGStudent1 : Student UGStudent2 : Student
studName = “Abdullah” studName = “Ah Cheong”
matricNumber = “60812” matricNumber = “93047” UML Notation
marks = 0.0 marks = 97.0 for Objects
CREATING OBJECT: STEP 1 EXAMPLE
CREATING OBJECT: STEP 2 INSTANTIATION SYNTAX
123 Syntax:
UGStudent UGStudent : Student
<objectName>
123
= new <ObjectType>(<parameter(s)>);
studentName = “Abdullah”
:
wherematricNumber = “60812”
marks = 0.0
- <objectName> – name of object
reference variable.
- <ObjectType> (<parameter(s)>) – constructor to set up the object.
UGStudent object
Example:
CREATING OBJECT IN ONE SINGLE STEP (WITH ACTUAL VALUES)
Syntax:
<ObjectType> <objectName> = new <ObjectType>(<parameter(s)>);
123
Example: UGStudent UGStudent : Student
123
studentName = “Abdullah”
matricNumber = “60812”
marks = 0.0
UGStudent object
CREATING OBJECT IN ONE SINGLE STEP
(USING USER’S INPUT)
123
UGStudent UGStudent : Student
123
studentName = “Ali”
matricNumber = “93047”
marks = 0.0
UGStudent object
Sample run:
CREATING OBJECT USING DEFAULT CONSTRUCTOR
public Student(){
}
The state of the UGStudent object after execution of the above code:
123
Student UGStudent
Student UGStudent : Student
-studentName: String UGStudent
class 123
-matricNumber: String studentName = null object
-marks: double matricNumber = null
marks = 0.0
MULTIPLE CONSTRUCTOR METHODS: EXAMPLE
The Student class has
two constructor methods
with different parameters.
CREATING OBJECT USING CONSTRUCTOR WITH ACTUAL VALUES
124
The state of UGStudent1 and UGStudent2 after the execution of above code:
123 UGStudent2
Student UGStudent1 UGStudent1 : Student UGStudent2 : Student
123 124
-studentName: String studentName = “Abdullah” studentName = “Ah Cheong”
-matricNumber: String matricNumber = “60812” matricNumber = “93047”
-marks: double marks = 0.0 marks = 97.0
Student class
UGStudent1 object UGStudent2 object
CREATING OBJECT USING USER’S INPUT
Sample run:
CREATING OBJECT USING USER’S INPUT – MEMORY STATE
The memory state of UGStudent1 and UGStudent2 after the execution of the code:
123 124
UGStudent1 UGStudent2
Student UGStudent1 : Student UGStudent2 : Student
123 124
-studentName: String studentName = “Ali” studentName = “Aminah”
-matricNumber: String matricNumber = “60812” matricNumber = “93047”
-marks: double marks = 0.0 marks = 89.0
Student class
UGStudent1 object UGStudent2 object
TWO OBJECTS USING ONE REFERENCE VARIABLE
student1 :Student student1 :Student
COPYING VARIABLES OF PRIMITIVE DATA TYPES
AND OBJECT TYPES
int i = 1;
int j = 2;
i = j;
j value will be copied to i
COPYING VARIABLES OF PRIMITIVE DATA TYPES
AND OBJECT TYPES
Student student1 = new Student(“Ahmad”, “s1111”);
Student student2 = new Student(“Siti”, “s2222”);
student1 = student2
student1 will refer to where student2 is currently referring to
Before After
student2
student2 student1
student1
student1 :Student student2 :Student
X student1 :Student student2 :Student
GARBAGE COLLECTION
As shown in the previous figure, after the assignment statement
student1 = student2, student1 points to the same object
referenced by student2. The object previously referenced by
student1 is no longer referenced. This object is known as garbage.
Garbage is automatically collected by JVM.
GARBAGE COLLECTION, CONT
TIP: If 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. Eg:
student1 = null;
ACCESSING OBJECT’S DATA
Referencing the object’s data:
[Link]
Example: to access the UGStudent1’s name and matric number
String name = [Link];
[Link]("Matric No. " +[Link]);
24
ACCESSING/INVOKING METHODS
• Once object is created, we can use the dot operator (.) to access its methods.
• Syntax to access or invoke void method:
<objectName>.<methodName(parameter(s))>;
• Syntax to access or invoke value returning method:
<variable> = <objectName>.<methodName(parameter(s))>;
[Link]("The value is"
+<objectName>.<methodName(parameter(s))>);
CAUTION
• Recall that you use the following to invoke a method in the Math class.:
[Link](arguments) (e.g., [Link](3, 2))
• Can you invoke determineGrade() using [Link]()? The answer is NO
because determineGrade() is a non-static method.
• All of the methods used before this are static methods, which are defined using the
static keyword.
• Non-static methods must be invoked from an object using:
[Link](arguments) (e.g., [Link]()).
RECALL: METHOD PARAMETERS
• Formal parameters
Part of method definition.
A formal parameter is a variable listed in the method’s header that receives the
actual parameter that is passed into a method.
• Actual parameters
An actual parameter is any piece of data that is passed into a method when the
method is called.
Must match data type
Must be in the same order
Multiple parameters can be passed sequentially into a parameter list.
ACCESSING VOID METHOD WITHOUT PARAMETERS
123
PGStudent PGStudent : Student
public void displayInfo() 123
{ studentName = “Ali”
[Link]("The name:" +studentName); matricNumber = “1189”
[Link]("The matric number:" +matricNumber); marks = 70.0
[Link]("The mark is: " +marks);
PGStudent object
[Link]("The grade is: " +determineGrade());
}
// Tester class
.......
Student PGStudent = new Student("Ali", "1189",70.0);//object creation
[Link](); //method call for void method
ACCESSING VALUE RETURNING METHOD WITHOUT PARAMETERS
123
public String determineGrade(){ PGStudent : Student
String grade; PGStudent
if (marks > 50) 123
grade="PASS"; studentName = “Ali”
else matricNumber = “1189”
grade="FAIL"; marks = 70.0
return grade;
} PGStudent object
// Tester class
.......
Student PGStudent = new Student("Ali","1189“,70.0);//object creation
grade = [Link](); //method call for value returning method
[Link]("The grade is " +grade); //print the outcome
OR
[Link]("Your grade is"+[Link]());//method call & print
in one line of code
ACCESSING VOID METHOD WITH PARAMETER
123
PGStudent PGStudent : Student
// Definition of method to assign student’s mark.
public void setMarks(double marks){ 123
[Link]=marks; studentName = “Ali”
} Formal Parameter matricNumber = “1189”
marks = 90.0
0.0
PGStudent object
// Invocation of the method (somewhere in main method)
...
Student PGStudent = new Student("Ali","1189");//object creation
[Link]("Enter marks");
double marks = [Link]();
[Link](marks);
}
Actual Parameter
ACCESSING VALUE RETURNING METHOD WITH PARAMETER
// Definition of method to calculate student’s fees
public double calculateFees(int totalCreditHours){
double fees;
fees = totalCreditHours * 100; Formal Parameter
return fees;
}
// Invocation of the method (somewhere in main method)
...
double fees;
int totalCreditHours = 22;
...
Student PGStudent = new Student("Ali","1189");//object creation
fees = [Link](totalCreditHours);//method call
[Link]("The fees is " +fees); //print the outcome
}
Actual Parameter
ACCESSING METHOD: EXAMPLE 1
Invoke method
setMark
(with parameter)
Invoke method
[Link](90.5); displayInfo
[Link]();
(without parameter)
ACCESSING METHODS: EXAMPLE 1
The state of UGStudent1
Output: after execution of the code:
123
UGStudent1
The name: Abdullah
UGStudent1 : Student
The matric number: 60812 123
The mark is: 90.5
studentName = “Abdullah”
The grade is: PASS
matricNo = “60812”
mark = 90.5
UGStudent1 object
ACCESSING METHOD: EXAMPLE 2
ACCESSING METHODS: EXAMPLE 2
Output: The state of rect1 after execution of the code:
123
rect1
123 rect1 : Rectangle
width= 10
length = 20
area = 200
perimeter = 60
rect1 object
HOW TO INVOKE toString() METHOD
Note that toString() method returns a String and it will not be displayed unless
printed by using [Link]();
2 ways to call toString() for UGStudent object:
Student UGStudent = new Student("Alia", "20000");
[Link]([Link]());
[Link](UGStudent);
NOTE
•An object cannot access its private members, as shown in (b). It is OK,
however, if the object is declared in its own class, as shown in (a) it can
be accessed eventhough it is private.
public class F { public class TestF {
private boolean x; public static void main(String[] args) {
F f = new F();
private int convert(boolean b) { [Link](f.x);
if (b == false) [Link]([Link](false));
return -1; }
else }
return 1;
}
public static void main(String[] args) {
F f = new F ();
[Link](f.x);
[Link]([Link](true));
} (b) This is wrong because x and convert are private in F.
}
37
A
c
c
e
s
s
M
o
d
i
f
i
e
r The private modifier restricts access to within a class, the default modifier restricts
s access to within a package, and the public modifier enables unrestricted access.