Professional Documents
Culture Documents
Instructor Name:
Lecture-5
Today’s Lecture
Components of Class
Fields
Methods
Main() Method, Setter Method, Getter Method, immutator.
2
Class & Methods
Messages to Object
“Start the
engine of the Object
BMW” <7_series_BMW>
Start_Engine
3
Class & Methods
Method of Class
Class
<CAR>
Start_Engine
4
Class & Methods
Behavior
Behavior is how an object acts and reacts, in terms of state changes and
interactions with other objects.
An operation is some action that one object performs upon another in order
to elicit a reaction.
5
Class & Methods
What is a Method?
Method defines the behaviour or basic functionality of the class.
return expression;
where expression is a Java expression that specifies the value you want to
return.
Method Examples
public class Dog {
private String name;
private int age;
Methods Invocation
Invoked as operations on objects/Class using the dot ( . ) operator
reference.method(arguments)
“Reference” can either be the class name or an object reference belonging to
the class
Inside the class: “reference” can be ommitted
10
Class & Methods
Methods Overloading
A class can have more than one method with the same
name as long as they have different parameter list.
public class Pencil {
. . .
public void setPrice (float newPrice) {
price = newPrice;
}
public void setPrice (Pencil p) {
price = p.getPrice();
}
}
12
Method Example – (Parameter is Object Reference)
class PassRef{
plainPencil
public static void main(String[] args) {
Pencil plainPencil = new Pencil("PLAIN"); color: PLAIN
System.out.println("original color: " +
plainPencil.color); plainPencil p
plainPencil p
System.out.println("new color: " +
plainPencil.color); color: RED
}
plainPencil p
public static void paintRed(Pencil p) {
color: RED NULL
p.color = "RED";
p = null;
- If you change any field of the object which the parameter refers to, the object is changed for
}
every variable which holds a reference to this object 13
}
- You can change which object a parameter refers to inside a method without affecting the original
reference which is passed
- What is passed is the object reference, and it’s passed in the manner of “PASSING BY VALUE”!
Class & Methods
Accessor usually contains the return statement in order to pass back that
information.
getName()
The most basic form of object is one that takes a single parameter whose
value is used to directly overwrite what is stored in the object’s field.
setName()
14
Class & Methods
Accessor Methods
15
Class & Methods
Mutator Methods
16
17