You are on page 1of 66

Chapter 4

Objects and Classes


Outlines
 Object variables
 Defining a class
 Instantiating and using objects
 Instance fields, Construction and methods

2
Introduction
 In procedural programming, data and operations on the data
are separate.

 Object-oriented programming places data and the operation


that pertain to them within a single entity called an Object.

 The object-oriented programming approach organizes in a way


that mirrors the real world, in which all objects are associated
with both attributes and activities.
 Object-oriented programming (OOP) involves programming using
objects.

3
Cont’d …
 Using objects improves software reusability and makes
program easier to develop and easier to maintain.

 Programming in java involves thinking in terms of


objects; a Java program can be viewed as a collection
of cooperating objects.

 An object represents an entity in the real world that


can be distinctly identified.

 For example, a student, a desk, a circle, a button, and


even a loan can all be viewed as objects.
4
Class Fundamentals
 A class is a template that defines the form of an

object.

 Specifies both the data and the code that will

operate on that data.

 Java uses a class specification to construct objects.

 Although there is no syntactic rule that enforces it,

a well-designed class should define one and only

one logical entity.


5
Cont…
 E.g a class that stores names and telephone
numbers will not normally also store information
about the stock market, average rainfall, sunspot
cycles, or other unrelated information

 Putting unrelated information into the same class


will quickly de structure your code!

 A main( ) method is required only if that class is


the starting

6 point for your program.


The General Form of a Class

class classname {

type var1; // declare instance variables


type var2;
// ...
type varN;

type method1(parameters) { // declare methods


// body of method
}
type method2(parameters) {
// body of method
}
// ...
type methodN(parameters) {
// body of method
}
}

7
Defining a Class

 To define a class you use the keyword class followed by


the name of the class, followed by a pair of braces
enclosing the details of the definition.

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

 A class contains what two things?

 What operator is used to access the members of a class


through an object?

 Each object has its own copies of the class’s ____

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.

 The above class diagrams are drawn according to the UML


(Unified Modeling Language) notations.
 Instance name is shown as instanceName:Classname and
underlined.
 Each object within a class retains its own states and behaviors.

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

 Explain what occurs when one object reference variable is


assigned to another.

 Assuming a class called MyClass, show how an object


called ob is created.

18
Methods

 A method contains one or more statements. In well-written


Java code, each method performs only one task.
 It used to achieve reusability of code, write once used
many times
 However, don’t use Java’s keywords for method names
 Syntax
return_type method_name (arg1, arg2…arg n)
{
//Executable code goes hear
{

19
Con’t…
 Naming method :While defining a method, remember that the
method name sould start with a lowercase letter.

 In the multi-word method name, the first letter of each word


must be in uppercase except the first word.
 E.g
sum(), area(), areaOfCircle(), stringComparision()

20
Con’t ….

 Types of Method: There are two types of methods in


Java:
• Predefined Method
• User-defined Method.

 In Java, predefined methods are the method that is already


defined in the Java class libraries.
 It is also known as the standard library method or built-in
method.

 Some pre-defined methods are length(), equals(),


compareTo(), sqrt(), etc
21
Constructors
 Additionally, a class provides a special type of methods,
known as constructors.
 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.

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;

public Counter() // Constructor


{
CounterIndex = 0;
}

public void increase() //Methods to update or access


counter
{
CounterIndex = CounterIndex + 1;
}
public void decrease()
{
CounterIndex = CounterIndex - 1;
}
int getCounterIndex()
{
return CounterIndex;
}
}27
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());
}
}

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;

public Counter() // Constructor 1


{
CounterIndex = 0;
}
public Counter(int InitValue ) // Constructor 2
{
CounterIndex = InitValue;
}
}
// A New User Class: Utilising both constructors
Counter c1 = new Counter();
Counter c2 = new Counter (10);

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;

aCircle = new Circle();


At creation time the center and radius are not
defined. These values are explicitly set later.

Constructors initialise Objects


Circle aCircle = new Circle(10.0, 20.0, 5.0);

aCircle is created with center(10,20) and radius 5

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 {

public static void main(String args[]){


Circle circleA = new Circle( 10.0,
12.0, 20.0);
Circle circleB = new Circle(10.0);

Circle circleC = new Circle();


}
}
circleA = new Circle(10, 12, 20) circleB = new Circle(10) circleC = new Circle()

Centre = (10,12) Centre = (0,0) Centre = (0,0)


Radius = 20 Radius=10 Radius = 1
36
Exercise
 Define a employee class
 Define Different Constructors
 Create objects per your constructors
 Access object properties and methods of your class
 Show method & constructor overloading

37
Variables of Primitive Data Types Vs. Object Types

Created using new Circle()


Primitive type int i = 1 i 1

Object type Circle c=new Circle() c reference c: Circle

radius = 1

Object type assignment c1 = c2


Primitive type assignment i = j Before: After:
Before: After:
c1 c1

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:

[FieldModifier(s)] returnType varName ;


 Constructors:
[Modifiers] ClassName(…){…}
 Member Methods:
[MethodModifier(s)] returnType methodName(…){…}

And even other classes



 Pedigree - extends, implements( …will see it later)
40
Data fields
 Data Fields are variables declared directly inside a class (not
inside method or constructor of a class)
 Data fields can be variables of primitive types or reference
types. public class Student {
 Example String name;
int age;
boolean isSci;
char gender;
}

 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);
}
}

Compilation error: variables not initialized

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.
}

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
{ year=y;} Instance
… variable

} 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.

Example: The constant PI in the Math class is defined as:

final static double PI = 3.14159265


 Static variables and methods can be used from instance or
static method in the class.
 Instance variables and methods can only be used from
instance methods, not from static methods.
 Static variables and methods belong to the class as a whole
and not to particular objects.
48
Cont’d …
Example:
public class Foo{
int i=5;
Static int k = 2;
public static void main(String[] args)
{ int j = i; // wrong i is instance variable
m1(); //wrong m1() is an instance method
}
public void m1()
{
i = i + k + m2(int i,int j); //Correct

}
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-

private’ or ‘default’ or ‘friendly’ access. )


 public

 Modifiers are applied by prefixing the appropriate keyword


for the modifier to the declaration of the class, variable,
method or constructor.
 Combinations of modifiers may be used in meaningful ways.
 The two levels are class level access modifiers and member
level access modifiers.

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’.

2. Member level access modifiers (variables and


methods)
 All the four public, private, protected and no modifer is
allowed.

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();
} } }
} } }

package p1; package p2;


class C1 { public class C2 { public class C3 {
... can access C1 cannot access C1;
} } can access C2;
}

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
?

You might also like