Objects and Classes
Objects and Classes
2
Introduction
In procedural programming, data and operations on the
data are separate.
5
The General Form of a Class
class classname {
// declare instance variables
type var1;
type var2;
// ...
type varN;
// declare methods
type method1(parameters) {
// body of method
}
type method2(parameters) {
// body of method
}
// ...
type methodN(parameters) {
// body of method
}
}
6
Cont…
Although there is no syntactic rule that enforces it, a well-
designed class should define one and only one logical entity
class Vehicle {
int passengers; // number of passengers
int fuelcap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon
}
8
Cont…
A class definition creates a new data type. In this
case, the new data type is called Vehicle.
9
Cont…
every Vehicle object will contain its own
copies of the instance variables passengers,
fuelcap, and mpg.
To access these variables, you will use the dot
(.) operator.
minivan.fuelcap = 16;
10
Progress Check
11
Object
An Object can be defined as an instance of a class.
An object has a unique identity, state, and behaviors.
The state defines the object, and the behavior defines what the
object does.
The state of an object consists of a set of data fields (also
known as properties) with their current values.
The behavior of an object is defined by a set of methods.
Example: A circle object has a data field, radius, which is
the property that characterizes a circle.
One behavior of a circle is that its area can be computed
using the method getArea().
12
Cont’d …
If you create a software object that models television.
The object would have variables describing the television's
current state, such as
Its status is on,
the current channel setting is 8,
the current volume setting is 23, and
The object would also have methods that describe the
permissible actions, such as
turn the television on or off,
change the channel,
change the volume, and etc.
13
Class and Instances
Objects of the same type are defined using a common class.
In other words, a class is a blueprint, template, or prototype that
defines and describes the attributes and behaviors common to
all objects of the same kind.
Class is objects with the same attributes and behavior .
A class can be visualized as a three-compartment box:
Name (or identity): identifies the class.
Variables (or attribute, state, field): contains the attributes of the
class.
Methods (or behaviour, function, operation): contains the dynamic
behaviours of the class.
14
Cont’d …
The followings figure shows a few examples of classes:
15
Cont’d …
An instance is a realization of a particular item of a class.
In other words, an instance is an instantiation of a class.
All the instances of a class have similar properties, as
described in the class definition.
For example, you can define a class called "Student" and
create two instances of the class "Student" for "Peter", and
"Paul“.
16
Cont’d …
The following figure shows two instances of the class Student.
Data Fields:
radius is _______
Methods:
getArea
19
Cont’d …
Concepts that can be represented by a class:
Tree
Building
Man Car
Animal Hotel
Student Computer Title Attributes
Author / Fields/
Book … PubDate Properties
ISBN
setTitle(…)
setAuthor (…)
setPubDate (…)
Methods/
setISBN (…)
Behavior
getTitle (…)
getAuthor (…)
…
20
How Objects Are Created
22
Con’t…
Naming method :While defining a method,
remember that the method name must be
a verb and start with a lowercase letter.
24
Constructors
Additionally, a class provides a special type of methods,
known as constructors, which are invoked to construct new
objects from the class.
Constructor is a special method that gets invoked
“automatically” at the time of object creation.
A constructor can perform any action, but constructors are
designed to perform initializing actions, such as initializing the
data field of objects.
Constructor is normally used for initializing objects with
default values unless different values are supplied.
When objects are created, the initial value of data fields is
unknown unless its users explicitly do so.
25
Cont’d …
In many cases, it makes sense if this initialization can be
carried out by default without the users explicitly initializing
them.
For example,
If you create an object of the class called “Counter”, it is
natural to assume that the counter record-keeping field is
initialized to zero unless otherwise specified differently.
In Java, this can be achieved through a mechanism called
constructors.
There are two types of constructors: default and
parametrized constructors
26
Cont’d …
Constructors has exactly the same name as the defining
class.
Like regular methods, constructor can be overloaded.(i.e. A
class can have more than one constructor as long as they
have different signature (different input parameter syntax).
This makes it easy to construct objects with different
initial data values.
Default constructor
If you don't define a constructor for a class, a default
parameter-less constructor is automatically created by
the compiler.
The default constructor calls the default parent
constructor (super()) and initializes all instance variables
to default value (zero for numeric types, null for object
references, and false for Booleans).
27
Cont’d …
Differences between methods and constructors.
Constructors must have the same name as the class itself.
Constructors do not have a return type—not even void.
Constructors are invoked using the new operator when an
object is created.
Defining a Constructor
public class ClassName {
// Data Fields…
// Constructor
public ClassName()
{
// Method Body Statements initialising Data Fields
}
//Methods to manipulate data fields
}
28
class MyClass {
int x;
MyClass() {
x = 10;
}
}
class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.x + " " + t2.x);
}
}
29
Cont’d …
class Circle {
/** The radius of this circle */
double radius = 1.0; Data field
// Constructor
public Counter()
{
CounterIndex = 0;
}
//Methods to update or access counter
public void increase()
{
CounterIndex = CounterIndex + 1;
}
public void decrease()
{
CounterIndex = CounterIndex - 1;
}
int getCounterIndex()
{
return CounterIndex;
}
}
31
Cont’d …
class MyClass {
public static void main(String args[])
{
Counter counter1 = new Counter();
counter1.increase();
int a = counter1.getCounterIndex();
counter1.increase();
int b = counter1.getCounterIndex();
if ( a > b )
counter1.increase();
else
counter1.decrease();
System.out.println(counter1.getCounterIndex());
}
}
32
Cont’d …
A Counter with User Supplied Initial Value ?
This can be done by adding another constructor method to the
class. public class Counter {
int CounterIndex;
// Constructor 1
public Counter()
{
CounterIndex = 0;
}
public Counter(int InitValue )
{
CounterIndex = InitValue;
}
}
// A New User Class: Utilising both constructors
Counter counter1 = new Counter();
Counter counter2 = new Counter (10);
33
Cont’d …
Adding a Multiple-Parameters Constructor to our Circle Class
public class Circle
{
public double x,y,r;
// Constructor
public Circle(double centreX, double centreY,double radius)
{
x = centreX;
y = centreY;
r = radius;
}
//Methods to return circumference and area
public double circumference()
{ return 2*3.14*r;
}
public double area()
{ return 3.14 * r * r;
34 }
}
Creating Objects Using Constructors
Objects are created from classes using new operator
ClassName objectRefVar = new ClassName([parameters]);
OR
ClassName objectRefVar ;
objectRefVar = new ClassName([parameters]);
The new operator creates an object of type ClassName.
The variable objectRefVar references the object .
The object may be created using any of its constructors
If it has constructors other than the default one
appropriate parameters must be provided to create objects
using them.
35
Cont’d …
Example:
/*Declare a reference variable and create an object using an
empty constructor */
Circle c1 = new Circle();
/*Declare a reference variable and create an object using
constructor with an argument */
Circle c2 = new Circle(5.0)
//Declare reference variables
Circle c3, c4 ;
/*Create objects and refer the objects by the reference
variables
c3 = new Circle();
c4 = new Circle(8.0);
36
Accessing Objects
Once objects have been created, its data fields can be
accessed and its methods invoked using the dot operator(.),
also known as the object member access operator.
Referencing the object’s data:
objectRefVar.data
e.g., myCircle.radius = 100;
Invoking the object’s method:
objectRefVar.methodName(arguments)
e.g., double area = myCircle.getArea();
This is why it is called "object-oriented" programming; the
object is the focus.
37
Cont’d …
Circle aCircle = new Circle();
aCircle.x = 10.0; // initialize center and radius
aCircle.y = 20.0
aCircle.r = 5.0;
38
Cont’d …
Sometimes want to initialize in a number of different ways, depending
on circumstance.
This can be supported by having multiple constructors having different
input arguments.
public class Circle {
public double x,y,r; //instance variables
// Constructors
public Circle(double centerX, double centerY,double
radius)
{
x = centreX; y = centreY; r = radius;
}
public Circle(double radius) { x=0; y=0; r = radius; }
public Circle() { x=0; y=0; r=1.0; }
41
Variables of Primitive Data Types Vs. Object Types
radius = 1
i 1 i 2
c2 c2
i 2 j 2
c1: Circle C2: Circle c1: Circle C2: Circle
radius = 5 radius = 9 radius = 5 radius = 9
42
Garbage Collection
The object becomes a candidate for automatic garbage
collection.
Java automatically collects garbage periodically and
releases the memory used to be used in the future.
That is the JVM will automatically collect the space if
the object is not referenced by any variable.
As shown in the previous figure, after the assignment
statement c1 = c2, c1 points to the same object referenced
by c2.
The object previously referenced by c1 is no longer referenced.
This object is known as garbage.
Garbage is automatically collected by JVM.
43
Classes Declaration
Class declaration has the following syntax
[ClassModifiers] class ClassName [pedigree]
{
//Class body;
}
Class Body may contain
Data fields:
The default value of a data field is null for a reference type, 0 for
a numeric type, false for a boolean type, and '\u0000' for a char
type.
Data fields can be initialized during their declaration.
However, the most common way to initialize data fields is inside
constructors.
45
Cont’d …
Java assigns no default value to a local variable inside a
method.
public class Test {
public static void main(String[] args) {
int x; // x has no default value
String y; // y has no default value
System.out.println("x is " + x);
System.out.println("y is " + y);
}
}
46
Types of Variables
Local variable: Created inside a method or block of statement
E.g. public int getSum(int a, int b)
{
int sum=0;
sum=a+b; This method has local variables such as a, b, sum.
return sum; Their scope is limited to the method.
}
Instance variable: Created inside a class but outside any method. Store
different data for different objects.
E.g.
public class Sample1 {
int year; This method has two instance variables year and month.
int month;
public void setYear(int y)
O1 Instanc
{ year=y;} e
… variabl
e
} Each object has its own data for the instance variable O2 Instanc
e
47 variabl
e
Cont’d …
Static variable: Created inside a class but outside any method. Store
one data for all objects/instances.
E.g. public class Sample {
static int year; This class has one static variable: year
int month;
public static void setYear(int y) {
year=y;}
Shared by
… } all objects/
instances
• Static/class variables store O1 O4
values for the variables in
common memory location. O5
• Because of this common O2 Static
location, all objects of the variable
same class are affected if one O6
object changes the value of a O stands for
Object
static variable. O3
48
Cont’d …
We define class variables by including the static keyword
before the variable itself.
Example: class FamilyMember {
static String surname = "Johnson";
String name;
int age;
... }
Instances of the class FamilyMember each have their own
values for name and age.
But the class variable surname has only one value for all family
members.
Change surname, and all the instances of FamilyMember are
affected.
49
Static/Class methods
Class methods, like class variables, apply to the class as a
whole and not to its instances.
Class methods are commonly used for general utility
methods that may not operate directly on an instance of
that class, but fit with that class conceptually.
For example, the class method Math.max() takes two
arguments and returns the larger of the two.
You don't need to create a new instance of Math; just call
the method anywhere you need it, like this:
int LargerOne = Math.max(x, y);
50
Cont’d …
Good practice in java is that, static methods should be
invoked with using the class name though it can be invoked
using an object.
ClassName.methodName(arguments)
OR
objectName.methodName(arguments)
General use for java static methods is to access static fields.
51
Cont’d …
Constants in class are shared by all objects of the class.
Thus, constants should be declared final static.
54
Modifiers in Java
Java provides a number of access modifiers to help you set the
level of access you want for classes as well as the fields,
methods and constructors in your classes.
Access modifiers are keywords that help set the visibility and
accessibility of a class, its member variables, and methods.
Determine whether a field or method in a class, can be used or
invoked by another method in another class or subclass.
Could one class Class Name2
Class Name1 directly access
Attribute area another class’s Attribute area
methods or
attributes?
Method area Method area
Encapsulation
55
Cont’d …
Access Modifiers
private
protected
no modifier (also sometimes referred as ‘package-
56
Cont’d …
1. Class level access modifiers (java classes only)
Only two access modifiers is allowed, public and no modifier
If a class is ‘public’, then it CAN be accessed from
ANYWHERE.
If a class has ‘no modifer’, then it CAN ONLY be accessed
from ’same package’.
57
Cont’d …
public access modifier
The class, data, or method is visible to any class in any package.
Fields, methods and constructors declared public (least
restrictive) within a public class are visible to any class in the
Java program, whether these classes are in the same package or
in another package.
private access modifier
The private (most restrictive) fields or methods can be
accessed only by the declaring class.
Fields, methods or constructors declared private are strictly
controlled, which means they cannot be accesses by anywhere
outside the enclosing class.
A standard design strategy is to make all fields private and
provide public getter and setter methods for them to read and
modify.
58
Cont’d …
protected access modifier
The protected fields or methods cannot be used for classes in
different package.
Fields, methods and constructors declared protected in a
superclass can be accessed only by subclasses in other
packages.
Classes in the same package can also access protected
fields, methods and constructors as well, even if they are not
a subclass of the protected member’s class.
No modifier (default access modifier)
Java provides a default specifier which is used when no
access modifier is present.
Any class, field, method or constructor that has no declared
access modifier is accessible only by classes in the same
package.
59
Cont’d …
For better understanding, member level access is formulated as a
table:
Same Other
Access Same Class Subclass
Package packages
Modifiers
public Y Y Y Y
protected Y Y Y N
no access
Y Y N N
modifier
private Y N N N
60
Cont’d …
Modifier Used on Meaning
61
Cont’d …
class Accessible only in its package
None
(package) interface Accessible only in its package
member Accessible only in its package
62
Cont’d …
class Accessible anywhere
64
Cont’d …
65
Cont’d …
package p1; package p2;
public class C1 { public class C2 { public class C3 {
public int x; void aMethod() { void aMethod() {
int y; C1 o = new C1(); C1 o = new C1();
private int z; can access o.x; can access o.x;
can access o.y; cannot access o.y;
public void m1() { cannot access o.z; cannot access o.z;
}
void m2() { can invoke o.m1(); can invoke o.m1();
} can invoke o.m2(); cannot invoke o.m2();
private void m3() { cannot invoke o.m3(); cannot invoke o.m3();
} } }
} } }
67
Con’t ….
There are a lot of usage of java this keyword
some of them:
Refer current class instance variable
Invoke current class method
Invoke current class constructor
Pass argument in method call
Pass argument in constructor call
68
Cont’d …
The most common reason for using the this keyword is
because a field is shadowed by a method or constructor
parameter. (to avoid name conflicts.)
Use this to refer to an instance data field. For example,
the Point class was written like this.
public class Point
{
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b)
{ x = a;
y = b; }
}
69
Cont’d …
but it could have been written like this:
public class Point {
public int x = 0;
public int y = 0;
//constructor public
Point(int x, int y)
{ this.x = x;
this.y = y;
} As we can see in the program that we have
} declare the name of instance variable and local
variables same. Now to avoid the confliction
70 between them we use this keyword.
Example
Class
Name
Data Filelds
Constructors
Initializing attributes
71
Cont’d …
From within a constructor, you can also use the this keyword to call
another constructor in the same class. Doing so is called an explicit
constructor invocation.
Use this to invoke an overloaded constructor of the same class.
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle()
{ this(0, 0, 0, 0); }
public Rectangle(int width, int height)
{ this(0, 0, width, height); }
public Rectangle(int x, int y, int width, int height)
{ this.x = x;
this.y = y;
this.width = width;
72 this.height = height; } }
Cont’d …
The no-argument constructor calls the four-argument
constructor with four 0 values.
The two-argument constructor calls the four-argument
constructor with two 0 values.
As before, the compiler determines which constructor to call,
based on the number and the type of arguments.
If present, the invocation of another constructor must
be the first line in the constructor.
73
Cont’d …
74
Getters and Setters Method
A class’s private fields can be manipulated only by
methods of that class.
So a client of an object—that is, any class that calls the
object’s methods—calls the class’s public methods to
manipulate the private fields of an object of the class.
Classes often provide public methods to allow clients of
the class to set (i.e., assign values to) or get (i.e., obtain
the values of) private instance variables.
The names of these methods need not begin with set or
get, but this naming convention is highly recommended in
Java.
75
Cont’d …
public class Circle {
private double x,y,r;
public double getX() { return x;}
public double getY() { return y;}
public double getR() { return r;}
public void setX(double x_in) { x = x_in;}
public void serY(double y_in) { y = y_in;}
public void setR(double r_in) { r = r_in;}
//Methods to return circumference and area
}
Better way of initialising or access data members x, y, r
To initialise/Update a value: aCircle.setX( 10 )
To access a value: aCircle.getX()
These methods are informally called as Accessors or Setters/Getters
Methods.
76
77
?