Building The Program: Iv. Class and Object of Java
Building The Program: Iv. Class and Object of Java
Learning Outcomes
At the end of this topic, the student is able to :-
i. Differentiate constructor and method
ii. Create new Java objects
iii. Manipulating objects
BEFORE WE START
+updatePosition(steps:int):int
currentPosition = currentPosition + steps;
return currentPosition;
}
• Reference Type
– Will be explain later
MORE ON TYPE
• Why?
– This is due to complexity of the object
– Implementing association, aggregation and composition relationship
pick
Player Token
Reference type
as instance variables
Player
- name:String
- cashInHand:double
- selectedToken : Token
+ updateCashInHand(amount:double) : void
cashInHand += amount;
}
CREATING OBJECT
• For example
Token wheelbarrow = new Token( );
new
Class Default
Object keyword
name constructor
+updatePosition(steps:int):int
DO IT THIS WAY
return currentPosition;
}
+updatePosition(steps:int):int
+updatePosition(steps:int):int
-name=?
created in memory
-currentPosition= 0
-color=?
+updatePosition(steps:int):int
• Object manipulation
– Assign value to object
– Retrieve value from object
– Ask object to do something
/*
What does this program do?
Put your answer here : ______________________________
*/
LET’S DO MORE!
wheelbarrow.name = “Wheelbarrow”;
wheelbarrow.color = “Grey”;
hat.name = “Hat”;
hat.color = wheelbarrow.color;
wheelbarrow.name = “Wheelbarrow”;
wheelbarrow.color = “Grey”;
hat.name = “Hat”;
hat.color = wheelbarrow.color;
}
}
/*
What does this program do?
Put your answer here : ______________________________
*/
}
BITP 3113 Object Oriented Programming
Sem I 2012/2013
3
Auhtored by Emma McKay-Fikri 4
>> Lesson 5
A Setter
• A Setter is a public method that will assign parameter value
to an instance variable.
this.name = name;
} Refers to name (instance
variable) in Token
wheelbarrow.setName(“Wheelbarrow”);
wheelbarrow.setColor(“Grey”);
System.out.print(“Name : “ + name);
System.out.println(“Color : “ + color);
METHOD LIKE
• Example
Constructor
• To initialize values
– To give initial values to instance variables.
this.name = name;
System.out.println(“Token “ + this.name + “ is created.”);
}
this.name = name;
System.out.println(“Token “ + this.name + “ is
created.”);
}
+updatePosition(steps:int):int
+updatePosition(steps:int):int
-name=“Ford”
created in memory
-currentPosition= 0
-color=“Grey”
+updatePosition(steps:int):int