0% found this document useful (0 votes)
19 views

Chapter 2. (Class Object)

The document discusses object-oriented programming concepts including classes, objects, and constructors. A class defines common attributes and behaviors for objects through data fields and methods. Constructors initialize new objects and can be overloaded for different initialization values. Objects are instances of a class and share its structure and behaviors.

Uploaded by

Abrham Tegegne
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Chapter 2. (Class Object)

The document discusses object-oriented programming concepts including classes, objects, and constructors. A class defines common attributes and behaviors for objects through data fields and methods. Constructors initialize new objects and can be overloaded for different initialization values. Objects are instances of a class and share its structure and behaviors.

Uploaded by

Abrham Tegegne
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 82

Object-Oriented Programming

Chapter Two: Class & Object


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

2
programming using objects.
Introduction

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.
3
Object
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().
4
Object, example
 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.
5
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 static attributes and
dynamic behaviors common to all objects of the same
kind.

Class is objects with the same attributes and behavior .


6
Class and Instances
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.

7
Class

In object-oriented programming, a class is a programming


language construct that is used as a blueprint to create
objects of that class.
 This blueprint describes what an object’s data and
methods will be.

An object is an instance of a class. The class that contains


that instance can be considered as the type of that object.

8
Class and Instances
The followings figure shows a few examples of classes:

9
Class and Instances
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“.

The term "object" is often used loosely, which may refer


10 to a class or an instance.
Class and Instances
The following figure shows two instances of the class Student.

The above class diagrams are drawn according to the UML


(Unified Modeling Language) notations.
A class is represented as a 3-compartment box, containing
name, variables, and method. Class name is shown in bold and
centralized. Instance name is shown as
11 instanceName:Classname and underlined.
Objects
Class…

Class Name: Circle A class template

Data Fields:
radius is _______

Methods:
getArea

Circle Object 1 Circle Object 2 Circle Object 3 Three objects of


the Circle class
Data Fields: Data Fields: Data Fields:
radius is 10 radius is 25 radius is 125

 . Each object within a class retains its own states and


behaviors.
12
Class….
The relationship between classes and object is analogous
to the relationship between apple recipes and apple pie.

A single class can be used to instantiate multiple objects.


This means that we can have many active objects or
instances of a class.

A class usually represent a noun, such as a person, place


or (possibly quite abstract) thing - it is a model of a
13
concept within a computer program.
Class…
Concepts that can be represented by a class:
Tree
Building
Man
Car
Animal
Hotel Title Attributes/
Student
Computer Author Fields/
Book PubDate Properties
… ISBN

setTitle(…)
setAuthor (…)
Methods/ setPubDate (…)
Behavior setISBN (…)

getTitle (…)
14 getAuthor (…)

Class…
A Java class uses variables to define data fields and
methods to define behaviors.

Variables and methods are called members of the class.

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.
15
Class…
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.
16
Constructors…
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 record-keeping field is
initialized to zero unless otherwise specified differently.

In Java, this can be achieved though a mechanism called


constructors.

17
Constructors
 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 arguments 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 parameterless
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
18
Booleans).(Inheritance…will see it later )
Constructors…

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.

19
Constructors…
Defining a Constructor
Like any other method
public class ClassName {

// Data Fields…

// Constructor
public ClassName()
{
// Method Body Statements initialising Data Fields
}

//Methods to manipulate data fields


}

20
Classes, Example
class Circle {
/** The radius of this circle */
double radius = 1.0; Data field

/** Construct a circle object */


Circle() {
}
Constructors
/** Construct a circle object */
Circle(double newRadius) { Overloading
radius = newRadius;
}

/** Return the area of this circle */


double getArea() { Method
return radius * radius * 3.14159;
}
}
21
Constructors…
Defining a Constructor: Example
public class Counter {
int CounterIndex;

// 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;
}
}
22
Constructors…
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());
}
}

23
Constructors…
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);
24
Constructors…
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; }
}

25
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 . An
object can be created with out using reference variables .
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
26
using them.
Creating Objects, Example
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);
27
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.
28
Constructors…

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.

29
Constructors…
Constructors initialise Objects
With defined constructor

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

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


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

30
Constructors…
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 centreX, double cenreY, 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; }

//Methods to return circumference and area


public double circumference() { return 2*3.14*r; }
31 public double area() { return 3.14 * r * r; }
}
Constructors…
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)


32 Radius = 20 Radius=10 Radius = 1
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

i 2 j 2
c1: Circle C2: Circle c1: Circle C2: Circle
radius = 5 radius = 9 radius = 5 radius = 9

33
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
34
garbage. Garbage is automatically collected by JVM.
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

35 Pedigree - extends, implements( …will see it later)
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
36 '\u0000' for a char type.
Data fields…
public class Test {
public static void main(String[] args) {
Student student = new Student();
System.out.println("name? " + student.name);
System.out.println("age? " + student.age);
System.out.println(" isSci? " + student.isSci);
System.out.println("gender? " + student.gender);
}
}

Data fields can be initialized during their declaration.


However, the most common way to initialize data
fields is inside constructors
37
Data fields…..
• 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


38
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;
return sum; This method has local
} variables such as a, b,
sum.
Their scope is limited to
the method.

39
Types of Variables
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
int month;
public void setYear(int y){ two instance
year=y; variables year and
} month.

}

40 .
Types of Variables
Static variable
 Created inside a class but outside any method. Store
one data for all objects/instamces.
E.g.
public class Sample {
static int year;
int month;
public static void setYear(int y) {
year=y;
}
… This class has
} one static
variable: year
41
Types of Variables
Shared by all
objects/instanc
O1 es O4

O2
O5
Static variable

O3 O6
O stands for Object
42
Instance vs. Static variables

O1 Instance O4
Instance variable
variable

Each object
has its own
data for the
instance Instance
variable variable
O2 Instance
variable O5

Instance
Instance variable
variable

O3 O6
O stands for Object
43
Member Methods
A method declared inside the class definition is a
member methed

Methods implement the behavior of classes


That is method is an operation which can modify an
objects behavior.
In other words, it is something that will change an object
by manipulating its variables.

Only an object's methods should modify its


variables
44
Instance Variables and Methods
Instance variables and methods (also called members)
are those associated with individual instances (or
objects) of a class.
Instance variables belong to a specific instance; it is not
shared among objects of the same class.
Example:
Circle cl = new Circle();
Circle c2 = new Circle(5);

The radius in c1 is independent of the radius in c2, and


is stored in different memory location. Change c1’s
radius do not affect c2’raduis and vice versa.
45
Instance Variables and Methods….
Instance methods are invoked by specific instance
of the class.
To get to the value of an instance variable or to
invoke instance methods, we use an expression in
what's called dot notation.
Example:
Circle cl = new Circle ();
cl.radius = 5;
System.out.println(“Area “ +
cl.getArea());

46
Static/class Variables…
 If we want all the instances of a class to share data, use
static variables.
 Static/class variables store values for the variables in
common memory location. Because of this common
location, all objects of the same class are affected if
one object changes the value of a static variable.
 With instance variables, each new instance of the
class gets a new copy of the instance variables that
class defines.

47
Static/class Variables…

 Each instance can then change the values of those


instance variables without affecting any other instances.
 With static/class variables, there is only one copy of
that variable. Every instance of the class has access to
that variable, but there is only one value. Changing the
value of that variable changes it for all the instances of
that class.

48
Static/class Variables…
 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 Variables…
 To access class variables, you use the same dot notation
as you do with instance variables.
 To get or change the value of the class variable, you
can use either the instance or the name of the class on
the left side of the dot. Both of the lines of output in
this example print the same value:
FamilyMember dad = new FamilyMember();
System.out.println("Family's surname is: " + dad.surname);
System.out.println("Family's surname is: " +
FamilyMember.surname);

50
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:

51
int LargerOne = Math.max(x, y);
Static/Class Methods
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.

52
Notes
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
53
whole and not to particular objects.
Notes
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(){


//Correct since instance and static variables and can be used in an
instance method.
i = i + k + m2(int i,int j);
}

public static int m2(int I, int j){


return (int)(Math.pow(i,j));
}
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.
55
Access modifiers
Access modifiers determine the visibility or
accessibility of an object’s attributes and methods to
other objects.
Could one class
directly access Class Name2
Class Name1
another class’s
methods or
attributes?
Attribute area
Attribute area

Method area
?
Encapsulation
Method area

56
Modifiers in Java
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.
57
Modifiers in Java
The two levels are class level access modifiers
and member level access modifiers.

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
58
accessed from ’same package’.
Modifiers in Java
2. Member level access modifiers (variables and
methods)

All the four public, private, protected and no modifer is


allowed.

59
Modifiers in Java
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.

60
Modifiers in Java
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
61
to read and modify.
Modifiers in Java
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.
62
Modifiers in Java
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.

63
Modifiers in Java
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

64
Modifiers in Java
First row {public Y Y Y Y} should be interpreted as:

Y:- A member declared with ‘public’ access modifier CAN be


accessed by the members of the ’same class’.
Y:- A member declared with ‘public’ access modifier CAN be
accessed by the members of the ’same package’.
Y: -A member declared with ‘public’ access modifier CAN be
accessed by the members of the ’subclass’.
Y:- A member declared as ‘public’ CAN be accessed from
‘Other packages’.

65
Modifiers in Java…
Modifier Used on Meaning
class Contains unimplemented methods and cannot
be instantiated.
Abstract interface All interfaces are abstract. Optional in
declarations
method No body, only signature. The enclosing class
is abstract
class Cannot be subclassed
method Cannot be overridden and dynamically
looked up
Final
field Cannot change its value. static final fields are
compile-time constants.
variable Cannot change its value.
native method Platform-dependent. No body, only signature
66
Modifiers in Java…
class Accessible only in its package
None
(package) interface Accessible only in its package
member Accessible only in its package

class Make an inner class top-level class


method A class method, invoked through the class
name.
static field A class field, invoked through the class name

one instance, regardless of class instances


created.
initializer Run when the class is loaded, rather than
when an instance is created.
67
private member Accessible only in its class(which defines it).
Modifiers in Java…
class Accessible anywhere

public interface Accessible anywhere


member Accessible anywhere its class is.

protected member Accessible only within its package and its


subclasses
class All methods in the class are implicitly
strictfp.

method All floating-point computation done is


strictfp strictly conforms to the IEEE 754 standard.
All values including intermediate results
must be expressed as IEEE float or double
68 values. It is rarely used.
Modifiers in Java…
method For a static method, a lock for the class is
synchronized acquired before executing the method. For a
non-static method, a lock for the specific
object instance is acquired.

transient field Not be serialized with the object, used with


object serializations.

volatile field Accessible by unsynchronized threads, very


rarely used.

•The table(matrix) in the next slide shows java


modifiers indicating summary of which modifier to
69
which element can be applied.
Modifiers in Java…

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

71
This keyword
a) 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.

72
This keyword
b) 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;
}
73
}
This keyword
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 =Asy;we can see in the program that we have
} declare the name of instance variable and local
} variables same. Now to avoid the confliction
74 between them we use this keyword.
Example
Class
Name

Data Filelds

Constructors

Initializing attributes

75
This keyword
c) 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.

76
This keyword
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;
this.height = height;
77 }
This keyword
For Example:
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.
78
This keyword…

79
Getters and Setters Methods
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
80 in Java
Getters and Setters Methods

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

81
Getters and Setters Methods
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.
82

You might also like