Chapter 4 - Objects and Classes e
Chapter 4 - Objects and Classes e
2
Introduction
In procedural programming, data and operations on the data
are separate.
3
Cont’d …
Using objects improves software reusability and makes
program easier to develop and easier to maintain.
object.
class classname {
7
Defining a Class
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.
Class declaration is only a type description; it does not
create an actual object.
The general form of a statement that does that is this:
ClassName variableName = new ClassName();
Each time you create an instance of a class, you are
creating an object that contains its own copy of each
instance variable defined by the class.
9
Cont…
Vehicle minivan = new Vehicle()
After this statement executes, minivan will be an instance
of Vehicle. Thus, it will have “physical” reality.
new operator dynamically allocates (that is, allocates at
run time) memory for an object and returns a reference to
it
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 filed, 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 our 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
there is no input coming from the remote control.
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
accept input from the remote control.
13
Class and Instances
Objects of the same type are defined using a common class.
Class define objects with the same attributes and behavior.
In other words, a class is a blueprint, template, or prototype
that defines and describes the static attributes and dynamic
behaviors common to all objects of the same kind.
A class can be visualized as a three-compartment box:
Name (or identity): identifies the class.
Variables (or attribute, state, field): contains the static
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 …
The following figure shows two instances of the class Student.
16
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 (…)
…
17
Progress Check
18
Methods
19
Con’t…
Naming method :While defining a method, remember that the
method name sould start with a lowercase letter.
20
Con’t ….
22
Cont’d …
In many cases, it makes sense if this initialisation 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 is initialized to zero
unless otherwise specified differently.
In Java, this can be achieved though a mechanism called
constructors.
23
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).
24
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
}
25
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);
}
}
26
Defining a Constructor: Example
public class Counter {
int CounterIndex;
System.out.println(counter1.getCounterIndex());
}
}
28
A Counter with User Supplied Initial Value
This can be done by adding another constructor method to the
class.
public class Counter {
int CounterIndex;
29
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;
30 }
}
Creating Objects Using Constructors
Objects are created from classes using new operator
ClassName 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.
31
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);
32
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.
33
Cont’d …
Circle aCircle = new Circle();
aCircle.x = 10.0; // initialize center and radius
aCircle.y = 20.0
aCircle.r = 5.0;
34
Cont’d …
Sometimes want to initialize in 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;
}
}
35
Cont’d …
Initializing with constructors
public class TestCircles {
37
Variables of Primitive Data Types Vs. Object Types
radius = 1
i 1 i 2
c2 c2
j 2 j 2
c1: Circle C2: Circle c1: Circle C2: Circle
radius = 5 radius = 9 radius = 5 radius = 9
38
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.
39
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.
41
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);
}
}
42
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.
}
} Each object has its own data for the instance variable O2
Instance
43 variable
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
44
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.
45
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);
46
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.
47
Cont’d …
Constants in class are shared by all objects of the class.
Thus, constants should be declared final static.
}
public static int m2(int I, int j)
{ return (int)(Math.pow(i,j)); }
49
}
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
50
Cont’d …
Access Modifiers
private
protected
no modifier (also sometimes referred as ‘package-
51
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’.
52
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.
53
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.
54
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
55
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();
} } }
} } }
56
This Keyword
Within an instance method or a constructor, this is a reference
to the current object (the object whose method or constructor
is being called)
Use this to refer to the object that invokes the instance
method.
57
Cont’d …
The most common reason for using the this keyword is to
avoid name conflicts between instance variable and local
variables.
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; }
58
}
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;
}
}
59
Example
Class
Name
Data Filelds
Constructors
Initializing attributes
60
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;
61 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.
62
Cont’d …
63
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.
64
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.
65
66
?