You are on page 1of 26

Classes and Objects

Everything is an Object

Anything that you can describe can be represented as an


object, and that representation can be created,
manipulated and destroyed to represent how you use
the real object that it models.

2
Defining an Object

An object is a self-contained entity


with attributes and behaviors

information an object must know: behavior an object must do:


 identity – uniqueness  methods – what it can do
 attributes – structure  events – what it responds to
 state – current condition

3
Thinking About Objects
Objects
Reusable software components that model real-world
items
Look all around you
 People, animals, plants, cars, etc.
Attributes
 Size, shape, color, weight, etc.
Behaviors
 Babies cry, crawl, sleep, etc.
Class as Abstraction
 A class is an abstraction of its
instances. It defines all the
attributes and methods that its
instances must also have.

Person

name
gender
age

tellGender()
tellAge()

5
Defining a Class
A Class acts as the template from which an instance of an
object is created. The class defines the properties of the
object and the methods used to control the object's behavior.
A Class specifies the structure of data as well as the methods
which manipulate that data. Such data and methods are
contained in each instance of the class.
A Class is a model or template that can be instantiated to
create objects with a common definition, and therefore
common properties, operations and behavior.
A Class provides a template for defining the behavior of a
particular type of object. Objects are referred to as
“instances” of a class.
6
Basic Terminology
A class defines a kind of objects:
specifies the kinds of attributes (data) an object of
the class can have.
provides methods specifying the actions an object
of the class can take.
An object is an instance of the class.
Person is a class
Alice and Bob are objects of the Person class.
Concept of Class and Object
“Class” refers to a blueprint. It defines the
variables and methods the objects support

“Object” is an instance of a class. Each object has


a class which defines its data and behavior
Class Members
A class can have three kinds of members:
 fields: data variables which determine the status of the
class or an object
 methods: executable code of the class built from
statements. It allows us to manipulate/change the status
of an object or access the value of the data member
 nested classes and nested interfaces
Fields – Declaration
Field Declaration
 a type name followed by the field name, and optionally an
initialization clause
 primitive data type
 boolean, char, byte, short, int, long, float, double
 field declarations can be preceded by different modifiers
 access control modifiers
 static
 final
Fields –Initialization
Field initialization
not necessary to be constants, as long as with the right
type
If no initialization, then a default initial value is assigned
depending on its type
Type Initial Value
boolean false
char ‘\u0000’
byte, short, int, long 0
float +0.0f
double +0.0
object reference null
final Variables
Final variables are named constants. They cannot be
modified
class CircleStuff {
static final double pi =3.1416;
}

Must be initialized when declared or in a constructor


Method Definitions
 Methods belong to a class
 Defined inside the class
 Heading
 Return type (e.g. int, float, void)
 Name (e.g. nextInt, println)
 Parameters (e.g. println(…) )
 More…
 Body
 enclosed in braces {}.
 Declarations and/or statements.
Methods – Invocation
Method invocations
 invoked as operations on objects/classes using the dot ( . )
operator
reference.method(arguments)
Method - 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 (int newPrice) {
price = newPrice;
}
}

 How does the compiler know which method you’re invoking?


— compares the number and type of the parameters and uses
the matched one
Methods – Parameter Values
 Parameters are always passed by value.
public void method1 (int a) {
a = 6;
}

public void method2 ( ) {


int b = 3;
method1(b);
}
Example Class
class Employee {
 // Fields
 private String name; //Can get but not change
 private double salary; // Cannot get or set
// Methods
 void pay () {
 System.out.println("Pay to the order of " +
 name + " $" + salary);
 }
public String getName() { return name; } // getter
}
Example Class

class Pencil {
public String color = “red”;
public int length;
public float diameter;

public void setColor (String newColor) {


color = newColor;
}
}
The Main Method - Concept
main method
 the system locates and runs the main method for a class
when you run a program
 other methods get execution when called by the main
method explicitly or implicitly
 must be public, static and void
Creating Objects
public static void main(String[] args)
 {
 Employee secretary; // declares secretary
 secretary = new Employee (); // allocates space
 Employee secretary = new Employee(); // does
both
But the secretary is still "blank" (null)
 secretary.name = "Adele"; // dot notation
 secretary.pay(); // sends a message
 }
Explicit Initializer
public class Point {
public int x = 0, y = 0;

public void move(int dx, int dy) {


x += dx; y += dy;
}
}

Public class Driver


{
public static void main(String[] args)
{
Point point1 = new Point(); // (0,0)
}
------------ Person.java ------ defining Person ---------------------
public class Person
{
private String _name;
private String _iceCream;

public void setName(String newName)


{
_name = newName; // this. is optional
}

public void setIceCream(String newIceCream) { … }

public void print()


{
System.out.println(_name + “ likes “ + _IceCream); // this. optional
}
}

------------ PersonTest.java ----- using Person ------------------


public class PersonTest
{
public static void main(String[] args)
{
Person joe = new Person();
joe.setName(“Joseph”);
joe.setIceCream(“Rocky Road”);

Person mary = new Person();


mary.setName(“Mary”);
mary.setIceCream(“Chocolate Fudge”);
mary.print();
}
}
Terminologies
instance = object
field = instance variable
method = function
sending a message to an object = calling a function
Procedural vs. Object-Oriented Programming
 The unit in procedural programming is function, and unit in
object-oriented programming is class
 Procedural programming concentrates on creating functions,
while object-oriented programming starts from isolating the
classes, and then look for the methods inside them.

figure1: procedural figure2: object-oriented


Inheritance - Introduction

super-class ParkingMeter

subclass or
extended class

DigitalParkingMeter AnalogParkingMeter
END

You might also like