Lecture 04
• Classes and Objects
Part I
Objectives
• Understand the world of object oriented programming
• Understand the difference between Object Oriented and Non
Object Oriented Programming
• You get to know the building blocks of Object Oriented Paradigm
• Understand how to write classes and create objects
• Understand how to work with attributes
• Understand methods and a class constructor
The Software Problem
The software projects you created in your previous
programming assignments:
• Had a small code base
• Did not require maintenance and upgrade once submitted to your
instructor
• Required minimal team interaction
But most real world software:
• Have large code base
• Is continuously modified(adding and modifying features, fixing bugs)
• Requires interaction between many people in a team
Procedural Vs Object Oriented
Programming
• Programming tasks: originate from the desire to solve a
particular problem
• What is there, in that dusty old procedural town ?
• In procedural programming your code is kept concise
• Program completes certain steps to achieve specific
results (Recipe)
• Think in terms of a series of steps to be taken
to achieve a goal
…
Key idea: the functions have no intrinsic
relationship with the data they operate on
Global data is separate from the functions: this is
the problem with the data they
It is easy to modify data outside your scope.
Access to data is uncontrolled and unpredictable.
…
Testing and debugging are much more
difficult.
If you need to change the shared
variable, adjustments have to be made
each place it appears in your code.
This is difficult to manage in large
systems.
…
• How is this handled in Object village?
• In OOP data and related functions are put together into an “Object”
• Data inside an object can be manipulated by calling the object’s
functions
• Data is locked away inside your objects and
• The object’s functions are the only means of accessing or using that
data.
• Objects never operate on shared or global data.
What Exactly is an Object?
Whenever you program in OOP languages, you are creating
a model of some part of a real world system.
The real – world is full of objects
e.g. your dog, TV set, table lamp, radio
The model is built up from a collection of objects that
appear in the problem domain or external world.
An object is an entity that is defined by both of the
following two terms
• Attributes and
• Behaviors
Understanding Objects
• Attributes: are the data stored within an
object
• Attributes contain the information that
differentiates between various objects.
• Attributes are also known as states
• Behavior: is what the object can do
• In OOP behaviors are contained in methods
Understanding Objects cont…
• Take the case of real-world objects, for example, dog:
States:
– name
– color
– breed
– hungry
• Behavior:
– Breathing
– fetching
– wagging tail
– barking
Understanding Objects cont…
• Real – world objects vary in complexity
• E.g. Table lamp has
• 2 possible states: On and Off
• 2 possible behaviors: Turn on and Turn Off
• In contrast the radio has
• 4 possible states: On, Off, current Volume and current Station
• Behaviors: Turn On, Turn Off, Increase Volume Decrease Volume,
Volume, Tune…
Understanding Objects cont…
Software Objects are similar to real –world objects
• They too consist of states and related behaviors
• A software object stores its states in variables called fields
• A software object exposes its states(performs operations)
through its behaviors called methods
• Methods operate on an object internal state and
• Methods serve as the primary mechanisms for object – to-
object communication
What Exactly is a Class ?
Cookie Dough
Class Template
A class is a grouping of
similar objects.
It describes a collection of
related objects
Classes can be thought of as
the template, or cookie
Objects
cutters, for objects
. Classes are the blue-print
from which objects are created
The difference between a Class and an Object
One class
JVM
A class is a blue print for an object.
It tells the virtual machine how to
make an object of that particular type.
Class
Each object made from that class has
many objects
its own values for the states(fields) of
that class.
Each object also has all of the
behaviors defined by that class.
Objects in Java
• A class defines a new type of Object.
• To create an Object type to represent a light
switch . . .
class LightSwitch {
// state and behavior here
}
Fields
• An Object's state is stored in variables
called fields.
• Fields are declared (and optionally
initialized) inside the braces of the class.
• Light switch example with a field . . .
class LightSwitch {
boolean on = true;
}
Methods
• An Object's behavior is defined by its
methods.
• Methods, like fields, are written inside the
braces of the class.
• Methods can access the fields (the state) of
their object and can change them.
Light Switch Example
class LightSwitch {
boolean on = true; // field
boolean isOn() { // returns
return on; // the state
}
void switch() { // changes
on = !on; // the state
}
}
Constructing Objects
• We use the new keyword to construct a
new instance of an Object
• We can assign this instance to a variable
with the same type of the Object
LightSwitch ls = new LightSwitch();
• Note: classes define new datatypes !
Using Fields and Methods
LightSwitch ls = new LightSwitch();
• To access the field of an instance of an
Object use instance.field
ls.on;
• To access the method of an instance use
instance.method(arguments)
ls.isOn();
ls.switch();
Example Using Light Switch
• What does this main method print out?
LightSwitch ls = new LightSwitch();
System.out.println(ls.on);
ls.switch();
System.out.println(ls.isOn());
true
false
Person Example
class Person {
String name = “Jamal”;
int age = 26;
String getName() { return name; }
void setName(String n) { name = n; }
int getAge() { return age; }
void setAge(int a) { age = a; }
boolean smellsBad(){return true;}
}
Constructing Person Objects
• To create an instance of the Person class with
a name of "George" and an age of 22.
Person george = new Person();
george.setName("George");
george.setAge(22);
• Can we create a Person that has the name
George and the age 22 from the moment it is
created?
• Answer: Yes!
Constructors
• Constructors are special methods used to
construct an instance of a class.
• They have no return type.
• They have the same name as the class of the
Object they are constructing.
• They initialize the state of the Object.
• Call the constructor by preceding it with the new
keyword.
Person Constructor
class Person {
String name;
int age;
Person(String n, int a) {
name = n;
age = a;
}
// . . .
}
• Now we can construct George as follows:
Person george = new Person("George", 22);
Default Constructor
• When you do not write a constructor in a
class, it implicitly has a constructor with no
arguments and an empty body.
class LightSwitch {
// Leaving out the constructor
// is the same as . . .
LightSwitch() {}
}
• Result: every class has a constructor.
Multiple Constructors
• A class can have multiple constructors
class LightSwitch {
boolean on;
LightSwitch() {
on = true;
}
LightSwitch(boolean o) {
on = o;
}
}
This Keyword
• Instance can refer to itself with the keyword this
class LightSwitch {
boolean on;
LightSwitch() {
this.on = true; //(same as on=true;)
}
LightSwitch(boolean on) {
this.on = on; // now we can distinguish between the
} // instance variable and local variable
}
Cascading Constructors
• A constructor can call another constructor with
this(arguments)
class LightSwitch {
boolean on;
LightSwitch() {
this(true);
}
LightSwitch(boolean on) {
this.on = on;
}
}
Classes Recap
• Classes have fields to store the state of the
objects in the class and methods to provide the
operations the objects can perform.
• We construct instances of a class with the
keyword new followed by a call a constructor
method of the class.
• We can assign an instance to a variable with a
datatype named the same as the class.
• If you do not provide a constructor, the class will
have one with no arguments and no statements
by default.
Apple Example
class Apple {
String color;
double price;
Apple(String color, double price) {
this.color = color;
this.price = price;
}
Apple(double price) {
this("green", price);
}
String getColor() { return color; }
double getPrice() { return price; }
void setPrice(double p) { price = p; }
}
Apple Quiz
• What will these lines print out?
Apple a = new Apple("red", 100.0);
System.out.println(a.getColor()); red
System.out.println(a.getPrice()); 100.0
a.setPrice(50.5);
System.out.println(a.getPrice()); 50.5
Apple b = new Apple(74.6);
System.out.println(b.getColor()); green
System.out.println(b.getPrice()); 74.6
b.setPrice(a.getPrice());
System.out.println(b.getPrice()); 50.5