18 CS302 IntroOOP
18 CS302 IntroOOP
OBJECT ORIENTED
PROGRAMMING (OOP)
CS302 – Introduction to Programming
University of Wisconsin – Madison
Lecture 18
Vehicle myCar;
Vehicle momsCar;
• Example:
private String name;
Modifiers
• An access modifier stipulates whether a
field or method can be accessed or called
by the user of the class
• Fields/methods denoted as private can
only be accessed by methods within the
class
• Fields/methods denoted as public can be
accessed by methods either within the
class or outside the class
Composition: Objects as Instance
Variables
• You may have noticed in the example:
class Car
{
// Instance variables
private String make;
private String model;
private int mileage;
}
String
“Ford”
Car
String make
mileage = 100
String model
myCar make
“Jeremy”
model
“Bartholomew”
“Jeremy” String
“Bartholomew” “Mustang”
String make
String model
More on Instance Variables
• Nearly all of class’s instance variables should
be private
• If we think of an object as a machine, the
instance variables represent the gears. We
don’t want to expose the gears to the user of
the machine.
• Instead, if we want to allow the user access to
the instance variables, we provide public
methods for accessing these instance
variables.
Instance Methods
• Similar to instance variables, objects of the
same class have the same instance methods
• Instance methods are method members that
use the object’s instance variables
• The code for an object’s instance methods are
defined in the object’s class
• An object’s instance methods have access to
ALL of its instance variables
Instance Method
class Car
{
// Instance variables
private String make;
private String model;
private int mileage;
// Instance method
public void printFullName
{
System.out.print(make + “ “ + model);
}
}
this
• In order for an object to refer to itself, Java
provides a reserved word, this, that is a
reference variable pointing to itself
• A class’s instance variable can be referenced
as a field of the this variable
• The this variable’s primary use is when an
instance variable is overshadowed by a
method’s parameter
When to use this
• This is primarily used when an object’s instance variable name
is overshadowed by a method’s parameter name
• Example:
class Car
{
private String make;