You are on page 1of 17

ECEG – 3142: Object Oriented Programming (OOP)

(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

Chapter 4
Classes and Objects
With the knowledge you now have of the basics of the Java programming language, you can learn to write your own
classes. In this chapter, you will find information about defining your own classes, including declaring member variables,
methods, and constructors. You will learn to use your classes to create objects, and how to use the objects you create.

4.1. Introduction
Object-oriented programming is modeled on how, in the real world, objects are often made up of many kinds
of smaller objects. This capability of combining objects, however, is only one very general aspect of object-
oriented programming. Object-oriented programming provides several other concepts and features to make
creating and using objects easier and more flexible, and the most important of these features is that of classes.

 A class is a template for multiple objects with similar features. Classes embody all the features of a
particular set of objects. When you write a program in an object-oriented language, you don’t define
actual objects. You define classes of objects.
 Object: An instance of a class is another word for an actual object. If classes are an abstract
representation of an object, an instance is its concrete representation.

Figure 4.1: The Tree class and tree instants

4.1.1. State and Behavior


Object-oriented programming (OOP) involves programming using objects. They are key to understanding
object-oriented technology. An object represents an entity in the real world that can be distinctly identified.
Look around right now and you'll find many examples of real-world objects. For example, a dog, a student, a
desk, a circle, a button, a bicycle, and even a loan can all be viewed as objects.

Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color,
breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current
pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes).
Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-
oriented programming.

Software objects are conceptually similar to real-world objects: they too consist of state and related behavior.
An object stores its state in fields (variables in some programming languages) and exposes its behavior through
methods (functions in some programming languages). Methods operate on an object's internal state and serve

DBU, Department of Electrical and Computer Engineering, 3th Year 1


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

as the primary mechanism for object-to-object communication. Hiding internal state and requiring all
interaction to be performed through an object's methods is known as data encapsulation — a fundamental
principle of object-oriented programming.

4.2. Classes
4.2.1. Class Declaration/Defining Classes
A class declaration defines a new named reference type and describe how it is implemented. A top level class
is a class that is not a nested class. A nested class is any class whose declaration occurs within the body of
another class or interface.

The syntax for declaring a Java class:

 A minimal class declaration which contains only the required components can be defined as:
class ClassName {
// Fields/Variables
// Constructors
// Methods
}

 More generally, class declarations have the following form:


ClassModifier class ClassName{
// Fields/Variables
// Constructors
// Methods
}
Where:
Class Modifiers: A class declaration may include class modifiers at the very beginning.
Modifiers are keywords that you add to those definitions to change their meanings. To use a
modifier, such as public, private, and a number of others that you will encounter later, you
include its keyword in the definition of a class, method, or variable.
‘class’: is a keyword used to declare a class that defines a new named reference type and its
implementation. Every class declaration contains keyword class followed immediately by the
class’s name.
ClassName: it can be any valid Java identifier. By convention, classes are named with the first
letter of each word in a class name is capitalized. For example, ComputeArea, Math, and
JOptionPane.
The class body: the area between the two braces, every class’s body is enclosed in a pair of
left and right braces ({and}). It may contain declarations of members of the class (fields and
methods and nested classes and interfaces), instance and static initializers, and constructors.
4.2.2. Class Body and Members
The class body contains all the code that provides for the life cycle of the objects created from the class:
constructors for initializing new objects, declarations for the fields that provide the state of the class and its
objects, and methods to implement the behavior of the class and its objects.

A class body may contain declarations of:

 Members of the class, that is,


- Fields

DBU, Department of Electrical and Computer Engineering, 3th Year 2


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

- Methods
- Nested classes, and
- Nested interfaces
 Constructors
 Instance initializers
 Static initializers
The members of a class include both declared and inherited members. Declared Members of a class are the
type's fields, methods, and nested types (nested classes and interfaces). They are declared in the body of the
class.

Constructors, static initializers, and instance initializers are not members and therefore are not inherited.

4.3. Fields (Member Variables)


A variable provides us with named storage that our programs can manipulate. It is a storage location and has
an associated type. You must declare all variables before they can be used. Each variable in Java has a specific
data type. The data type is either a primitive type (such as byte, short, int, double, char, boolean) or a reference
type (class type, interface type, Array type).

4.3.1. Java Variable Types


There are several kinds of variables:

Instance Variables (Non-Static Fields):


- Non-static fields are also known as instance variables
- Instance variables are fields declared within a class declaration without using the keyword
static
- Instance variables are declared in a class, but outside a method, constructor or any block.
- objects store their individual states in "non-static fields", their values are unique to each
instance of a class (to each object
- Instance variables are created when an object is created with the use of the keyword 'new'
and destroyed when the object is destroyed.
- For every Non-Static Field declared in a class declaration, a new instance variable is created
and initialized to a default value as part of each newly created object of class
- They have default values. For numbers, the default value is 0, for Booleans it is false, and for
object references it is null.
Class Variables (Static Fields)
- A class variable is any field declared with the static modifier; this tells the compiler that there
is exactly one copy of this variable in existence, regardless of how many times the class has
been instantiated.
- Class variables also known as static variables
- They are declared with the static keyword in a class, but outside a method, constructor or a
block.
- Static variables are created when the program starts and destroyed when the program stops.
- Default values are same as instance variables. For numbers, the default value is 0; for
Booleans, it is false; and for object references, it is null.
Local Variables
- Local variables are declared in methods, constructors, or blocks.
- are created when the method, constructor or block is entered and the variable will be
destroyed once it exits the method, constructor, or block
- Access modifiers cannot be used for local variables.
DBU, Department of Electrical and Computer Engineering, 3th Year 3
ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

- Local variables are visible only within the declared method, constructor, or block. They are not
accessible from the rest of the class.
- There is no default value for local variables, so local variables should be declared and an initial
value should be assigned before the first use.
Parameters: name argument values passed to a method or a constructor. For example; in the main
method, the args variable is the parameter to this method. Parameters are always classified as
"variables" not "fields". This applies to other parameter such as lambda expression and exception
handlers.

Example: Different Kinds of Variables

public class MyClass{


static int numPoints; // numPoints is a class variable
int x, y; // x and y are instance variables

public int adder(int a, int b) { // a and b are method parameter


int sum = 0; // sum is a local variable
sum=a+b;
return sum;
}

public static void main(String[] args){

}
}

4.3.2. Field declarations


The variables of a class type are introduced by field declarations. Fields, or class variables, can be declared
inside the class body to store data. The syntax for declaring fields:

FieldModifier datatype fieldName; // or


FieldModifier datatype fieldName1, fieldName2, … fieldNameN;
Where:

 Field Modifier: are keywords that you add to those definitions to change their meanings. Zero or more
modifiers
 Access Control Modifiers: used to set access levels, i.e. what other classes have access to a
member field. The four access levels are:
 The default: Zero/ No modifiers are needed. Visible to the package,
 Public: Visible to the world; the field is accessible from all classes.
 Private: Visible to the class only; the field is accessible only within its own class
 Protected: Visible to the package and all subclasses
 Non-Access Modifiers: Java provides a number of non-access modifiers to achieve many
other functionality. Such as, static, final, transient, volatile.
 Data Type: All variables must have a type. You can use primitive types such as int, float, boolean, etc.
Or you can use reference types, such as strings, arrays, or objects.
 Field Name: All variables, whether they are fields, local variables, or parameters, follow the same
naming rules and conventions that were covered in the

DBU, Department of Electrical and Computer Engineering, 3th Year 4


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

4.4. Methods
A Java method is a collection of statements that are grouped together to perform an operation. The method
is for creating reusable code. Methods enable code sharing and reuse. In earlier chapters you have used
predefined methods such as System.out.println. When you call the System.out.println() method, for example,
the system actually executes several statements in order to display a message on the console.

 All the statements in Java must reside within methods. Methods are similar to functions except they
belong to classes. A method has a return value, a name and usually some parameters initialized
when it is called with some arguments.
 A method declares executable code that can be invoked, passing a fixed number of values as
arguments.
4.4.1. Defining a Method
A method definition consists of a method header and a method body. The syntax for defining a method is as
follows:

modifier returnValueType methodName(list of parameters){


// Method body;
}
The syntax shown above includes:

 Modifier − It defines the access type of the method and it is optional to use. Such as public, private,
and others you will learn about later.
 Return Value Type: is the data type of the value the method returns.
- It can be:
 Primitive types: such as int, float, boolean, etc.;
 Reference types: such as strings, arrays, or objects, or
 The keyword void.
- Some methods perform desired operations without returning a value.
 In this case, the return Value Type is the keyword void.
 This kind of method is known as void method.
 Example: the main method, System.out.println, etc.
- A method may return a value. If a method returns a value, it is called a value returning
method. A return statement is required for a value-returning method.
 Method Name: is any legal identifier.
- By convention, method names should be a verb in lowercase. If a name consists of several
words, concatenate them into one, making the first word lowercase and capitalizing the first
letter of each subsequent word.
 For example: run, runFast, getFinalData, etc.
- A method has a unique name within its class. However, a method might have the same name
as other methods due to method overloading.
 Parameter List: refers to the type, order, and number of the parameters of a method.
- It is a comma-delimited list of input parameters, enclosed by parentheses, ().
- They are optional; that is, a method may contain no parameters. If there are no parameters,
you must use empty parentheses.
- You need to declare a separate data type for each parameter. For instance, max(int num1, int
num2) is correct, but max(int num1, num2) is wrong.
- The variables declared in the method definition are known as formal parameters or simply
parameters. They like a placeholder.

DBU, Department of Electrical and Computer Engineering, 3th Year 5


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

- When a method is invoked, you pass a value to the parameter. This value is referred to as an
actual parameter or argument.
 Method Body: contains a collection of statements that define what the method does.
- It is the method's code enclosed between braces, {}.
- The variables declared in the method body are known as local variables.
- For a value-returning method, a return statement using the keyword return is required. The
method terminates when a return statement is executed.
Example:
Let’s look at a method created to find which of two integers is bigger. This method, named max, has two int
parameters, num1 and num2, the larger of which is returned by the method. The following Figure illustrates
the components of this method.

Here:

A method definition consists of a method header and a method body.


The method header specifies the modifiers, return value type, method name, and parameters of the
method.
The method name and the parameter types together constitute the method signature.
Accordingly, for the above method:

Method header: public static int max(int num1, int num2)


Method Signature: max(int, int)
Modifier: public static
Return value type: int
Method name: max
Parameter list: int num1, int num2
o Formal parameters: num1, num2
o Actual parameters/Arguments: x, y

4.4.2. Method Calling


A method definition is for creating a method, it define what the method is to do. To use a method, you have
to call or invoke it.

The syntax for method calling:

DBU, Department of Electrical and Computer Engineering, 3th Year 6


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

methodName(actual parameters)

There are two ways to call a method, depending on whether the method returns a value or not.
o If the method returns a value, a call to the method is usually treated as a value. For example:
int larger = max(3, 4);
System.out.println(max(3, 4));
o If the method returns void, a call to the method must be a statement. For example, the
method println returns void. The following call is a statement:
System.out.println("Welcome to Java!");
When a program calls a method, program control is transferred to the called method. A called method
returns control to the caller when its return statement is executed or when its method ending closing
brace is reached.
o A return statement is required for a value-returning method.
o A return statement is not needed for a void method, but it can be used for terminating the
method and returning to the method’s caller. The syntax is simply return;
Example:
Following is the example to demonstrate how to define a method and how to call it.

public class Example{


// the main method
public static void main(String[] args){
int i = 5;
int j = 2;
int k = max(i, j); // method calling: invoke max
System.out.println("The maximum between "+i+"and"+j+"is"+k);
}

// method definition for method max


public static int max(int num1, int num2){
int result;
if (num1 > num2)
result = num1;
else
result = num1;
return result;
}
}
This will produce the following result:

The maximum between 5 and 2 is 5


Note that:

This program contains the main method and the max method. The main method is just like any other
method except that it is invoked by the JVM.
In this example, the main method invokes max(i, j) , which is defined in the same class with the main
method.
When the max method is invoked, variable i’s value 5 is passed to num1, and variable j’s value 2 is
passed to num2 in the max method. The flow of control transfers to the max method. The max method
is executed. When the return statement in the max method is executed, the max method returns the
control to its caller (in this case the caller is the main method). This process is illustrated in the Figure
bellow.

DBU, Department of Electrical and Computer Engineering, 3th Year 7


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

4.4.3. A void Method


The void keyword allows us to create methods which do not return a value. Here, in the following example
we're considering a void method printGrade.

 This method is a void method, which does not return any value.
 Call to a void method must be a statement i.e. printGrade(93.5);.
- It is a Java statement which ends with a semicolon as shown in the following example.
public class ExampleVoid{
public static void main(String[] args){
printGrade(93.3);
}

public static void printGrade(double points){


if(points >= 90){
System.out.println(‘A’);
}
else if(points >= 80){
System.out.println(‘B’);
}
else{
System.out.println(‘C’);
}
}
}
This will produce the following result:
A
 To see the differences between a void and a value-returning method, let us redesign the
printGrade method to return a value. The new method, which we call getGrade, returns the grade
as shown below:
public class ExampleVoid{
public static void main(String[] args){
System.out.println(getGrade(93.3));
}

public static char getGrade(double points){


if(points >= 90){
return 'A';
}

DBU, Department of Electrical and Computer Engineering, 3th Year 8


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

else if(points >= 80){


return 'B';
}
else{
return 'C';
}
}
}
This will produce the following result:
A

4.4.4. Passing Parameters by Values


 When calling a method, you need to provide arguments, which must be given in the same order
as their respective parameters in the method signature.
- This is known as parameter order association.
- The arguments must match the parameters in order, number, and compatible type, as
defined in the method signature.
 For example, the following method prints a message n times:
public static void nPrintln(String message, int n){
for(int i = 0; i < n; i++)
System.out.println(message);
}
 Here:
- You can use nPrintln("Hello", 3) to print "Hello" three times.
- However, the statement nPrintln(3, "Hello") would be wrong. The data type of 3 does
not match the data type for the first parameter, message, nor does the second
parameter, "Hello", match the second parameter, n.
 When you invoke a method with a parameter, the value of the argument is passed to the
parameter. This is referred to as pass-by-value.
- If the argument is a variable rather than a literal value, the value of the variable is
passed to the parameter.
- The variable is not affected, regardless of the changes made to the parameter inside the
method.
- For Example:
public class Increment {
public static void main(String[] args) {
int x = 1;
System.out.println("Before the call, x is " + x);
System.out.println("after the call, x is " + x);
}

public static void increment(int n){


System.out.println("n inside the method is " + n);
}
}
This will produce the following result:
Before the call, x is 1
n inside the method is 2

DBU, Department of Electrical and Computer Engineering, 3th Year 9


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

after the call, x is 1

4.4.5. Overloading Methods


The Java programming language supports overloading methods, and Java can distinguish between
methods with different method signatures. This means that methods within a class can have the same
name if they have different parameter lists.
 When a class has two or more methods by the same name but different parameters, it is
known as method overloading.
 Overloaded methods must have different parameter lists (number, type, order).
public class MyClass{
. . .
public static double max(double num1, double num2){
. . .
}
public static double max(double num1, double num2, double num3){
. . .
}
public static double max(int num1, int num2){
. . .
}
public static double max(double num1, int num2){
. . .
}
}

 You cannot overload methods based on different modifiers or return types, i.e., you cannot
declare two methods with the same signature even if they have a different return type.
 You cannot declare more than one method with the same name and the same number and
type of arguments, because the compiler cannot tell them apart.
 Overloaded methods are differentiated by the number and the type of the arguments passed
into the method. The Java compiler determines which method is used based on the method
signature.
- For Example: max(1, 2.5), max(1.2, 2.3, 4.3) and max(1.2, 3,5) are distinct and unique
methods because they require different argument types.

4.5. Constructors
A class contains constructors that are invoked to create objects from the class blueprint. Constructor
declarations look like method declarations—except that they use the name of the class and have no return
type.

A constructor initializes an object when it is created.


It has the same name as its class.
It is syntactically similar to a method. However, constructors have no explicit return type.
Constructors are invoked using the new operator when an object is created.
All classes have constructors, whether you define one or not, because Java automatically provides a default
constructor that initializes all member variables to zero.

DBU, Department of Electrical and Computer Engineering, 3th Year 10


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

When a class is declared without any explicitly defined constructor, a default constructor is provided
automatically.
o It is a no-argument constructor with an empty body.
o However, once you define your own constructor, the default constructor is no longer used.
Syntax: Following is the syntax of a constructor

public class ClassName{


. . .
public ClassName() {
}
. . .
}

Java allows two types of constructors namely:

No argument Constructors: it does not accept any parameters.


Parameterized Constructors: a constructor that accepts one or more parameters. Parameters are
added to a constructor in the same way that they are added to a method, just declare them inside the
parentheses after the constructor's name.
Constructors are used to construct objects. To construct an object from a class, invoke a constructor of the
class using the new operator, as follows:

new ClassName(arguments);
For example, the following class has two constructors: one no argument constructor and a parameterized
constructor; as follow:

public class ClassName{


// fields
int num1;
int num2;

// no arg constructor
public ClassName() {
num1=12;
num2=34;
}

// a parameterized constructor
public ClassName(int x, int y) {
num1=x;
num2=y;
}
. . .
}

4.6. Creating Objects


As mentioned previously, a class provides the blueprints for objects. So basically, an object is created from a
class. In Java, the new keyword is used to create new objects.

When you write a Java program, you define a set of classes. Classes are templates for objects; for the most
part, you merely use the class to create instances and then work with those instances.
DBU, Department of Electrical and Computer Engineering, 3th Year 11
ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

There are three steps when creating an object from a class:

 Declaration: Declaring a Variable to Refer to an Object


 Instantiation: The 'new' keyword is used to create the object.
 Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes the new
object.
Step1: Declaration
To create an object from a class, first you should declare a variable to refer the object. Such variables are
known as reference variables, which contain references to the objects. Previously, you learned that to declare
a variable.

Similarly, reference variables are declared using the following syntax:

ClassName refVarName;
Where:

- ClassName is the name of the class you want to create an instance of. A class is essentially a
programmer-defined type. A class is a reference type, which means that a variable of the class type
can reference an instance of the class.
- reVarName: is any valid Java identifier.
- For example: The following statement declares the variable myCircle to be of the Circle type:
Circle myCircle;
Simply declaring a reference variable does not create an object. It is just a variable declarations that associate
a variable name with an object type. A variable in this state, which currently references no object. You must
assign an object to myCircle before you use it in your code. Otherwise, you will get a compiler error. For that,
you need to use the new operator, as described in the next section.
Step 2: Instantiation a Class
 The 'new' keyword is a Java operator that creates the object. It instantiates a class by allocating
memory for a new object and returning a reference to that memory. The new operator also invokes
the object constructor.
 Note: The phrase "instantiating a class" means the same thing as "creating an object." When you
create an object, you are creating an "instance" of a class, therefore "instantiating" a class.
 The new operator requires a single, postfix argument: a call to a constructor. The name of the
constructor provides the name of the class to instantiate.
 The new operator returns a reference to the object it created. This reference is usually assigned to a
variable of the appropriate type, like:
Circle myCircle;
myCircle=new Circle();
 The reference returned by the new operator does not have to be assigned to a variable. It can also
be used directly in an expression. For example:
int x= new Circle().radius;

Step 3: Initializing an Object


 The 'new' keyword is followed by a call to a constructor. This call initializes the new object.
 Constructor lets you provide initial values for the object, using both primitive and reference types. If
a class has multiple constructors, they must have different signatures. The Java compiler
differentiates the constructors based on the number and the type of the arguments.

DBU, Department of Electrical and Computer Engineering, 3th Year 12


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

 All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler
automatically provides a no-argument constructor, called the default constructor. This default
constructor calls the class parent's no-argument constructor, or the Object constructor if the class
has no other parent. If the parent has no constructor (Object does have one), the compiler will reject
the program.
 Using the syntax shown below, you can write a single statement that combines the declaration of an
object reference variable, the creation of an object, and the assigning of an object reference to the
variable.
ClassName refVarName=new ClassName(arguments);

4.7. Using Objects: Accessing an Object’s Fields and Methods


Once you've created an object, you probably want to use it for something. You may need to use the value of
one of its fields, change one of its fields, or call one of its methods to perform an action. After an object is
created, its data can be accessed and its methods invoked using the dot operator (.), also known as the object
member access operator

4.7.1. Accessing Instance Variables


Instance variables also known as non-static variables are declared without the static keyword in a class, but
outside a method, constructor or a block. Their values are unique to each instance of a class (to each object,
in other words). Technically speaking, objects store their individual states in "non-static fields".

Instance variables can be accessed directly by calling the variable name inside the class. To refer an object's
fields, you can use the following syntax:

refVarName.fieldName;

4.6.2. Accessing Class Variables


Class variables also known as static variables are declared with the static keyword in a class, but outside a
method, constructor or a block. A class variable is any field declared with the static modifier; this tells the
compiler that there is exactly one copy of this variable in existence, regardless of how many times the class
has been instantiated.

Static variables can be accessed by calling with the class name, as follow:

ClassName.fieldName;

Example: Accessing Instance & Class Variables


This example explains how to access instance variables and class variables of a class.

public class ClassOne{


int num1;
int num2=12;
static int num3=23;
}

DBU, Department of Electrical and Computer Engineering, 3th Year 13


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

public class ClassTwo{


public static void main(String[] args){
int x;
int y;
int m;
ClassOne myClass=new ClassOne();
x=myClass.num1;
y=myClass.num2;
m=ClassOne.num3;
System.out.println("x="+x+" y="+y+" m="+m);
}
}
The expected output:

X=0 y=12 m=23

4.7.3. Calling an Object's Methods


You also use an object reference to invoke an object's method. You append the method's simple name to the
object reference, with an intervening dot operator (.). Also, you provide, within enclosing parentheses, any
arguments to the method. If the method does not require any arguments, use empty parentheses.

refVarName.methodName(arguments); // or
refVarName.methodName();

Example:
public class ClassOne{
int num1=32;
int num2=12;

public int adder(){


return num1+num2;
}
}

public class ClassTwo{


public static void main(String[] args){
int x;
ClassOne myClass=new ClassOne();
x=myClass.adder();
System.out.println("x="+x);
}
}
The expected output:

X=44
Note

A class can have references to objects of other classes as members. This is called composition and is
sometimes referred to as a has-a relationship.
DBU, Department of Electrical and Computer Engineering, 3th Year 14
ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

4.8. Using the 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. You can refer to any member of the current object from within an
instance method or a constructor by using this.

4.8.1. Using ‘this’ with a Field


The most common reason for using the ‘this’ keyword is because a field is shadowed by a method or
constructor parameter. 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;
}
}
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;
}
}
Each argument to the constructor shadows one of the object's fields — inside the constructor x is a local copy
of the constructor's first argument. To refer to the Point field x, the constructor must use this.x.

4.8.2. Using this with a Constructor


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. Here's another Rectangle class.

public class Rectangle {


private int x, y;
private int width, height;

public Rectangle() {
this(0, 0, 1, 1);
}
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;
}

DBU, Department of Electrical and Computer Engineering, 3th Year 15


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

...
}
This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member
variables. The constructors provide a default value for any member variable whose initial value is not provided
by an argument. For example, the no-argument constructor creates a 1x1 Rectangle at coordinates 0,0. The
two-argument constructor calls the four-argument constructor, passing in the width and height but always
using the 0,0 coordinates. As before, the compiler determines which constructor to call, based on the number
and the type of arguments.

4.9. Controlling Access to Members of a Class


Access level modifiers determine whether other classes can use a particular field or invoke a particular
method. There are two levels of access control:

 At the top level—public, or package-private (no explicit modifier).


 At the member level—public, private, protected, or package-private (no explicit modifier).
A class may be declared with the modifier public, in which case that class is visible to all classes everywhere.
If a class has no modifier (the default, also known as package-private), it is visible only within its own package
(packages are named groups of related classes).

At the member level, you can also use the public modifier or no modifier (package-private) just as with top-
level classes, and with the same meaning. For members, there are two additional access modifiers: private
and protected. The private modifier specifies that the member can only be accessed in its own class. The
protected modifier specifies that the member can only be accessed within its own package (as with package-
private) and, in addition, by a subclass of its class in another package.

The following table shows the access to members permitted by each modifier.

Access Levels

Modifier Class Package Subclass World

public Y Y Y Y

protected Y Y Y N

no modifier Y Y N N

private Y N N N

The first data column indicates whether the class itself has access to the member defined by the access level.
As you can see, a class always has access to its own members. The second column indicates whether classes
in the same package as the class (regardless of their parentage) have access to the member. The third column
indicates whether subclasses of the class declared outside this package have access to the member. The fourth
column indicates whether all classes have access to the member.

4.10. The Static and final key words


static Class Members
Every object has its own copy of all the instance variables of the class. In certain cases, only one copy of a
particular variable should be shared by all objects of a class. A static field—called a class variable—is used in

DBU, Department of Electrical and Computer Engineering, 3th Year 16


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

such cases. A static variable represents class wide information—all objects of the class share the same piece
of data. The declaration of a static variable begins with the keyword static.

Use a static variable when all objects of a class must use the same copy of the variable.

Static variables have class scope. We can access a class’s public static members through a reference to any
object of the class, or by qualifying the member name with the class name and a dot (.), as in Math.random()
. A class’s private static class members can be accessed by client code only through methods of the class.
Actually, static class members exist even when no objects of the class exist—they’re available as soon as the
class is loaded into memory at execution time. To access a public static member when no objects of the class
exist (and even when they do), prefix the class name and a dot (.) to the static member, as in Math.PI. To
access a private static member when no objects of the class exist, provide a public static method and call it by
qualifying its name with the class name and a dot.

A static method cannot access non-static class members, because a static method can be called even when no
objects of the class have been instantiated. For the same reason, the this reference cannot be used in a static
method. The this reference must refer to a specific object of the class, and when a static method is called,
there might not be any objects of its class in memory.

final Instance Variables


The principle of least privilege is fundamental to good software engineering. In the context of an application,
it states that code should be granted only the amount of privilege and access that it needs to accomplish its
designated task, but no more. This makes your programs more robust by preventing code from accidentally
(or maliciously) modifying variable values and calling methods that should not be accessible.

Let’s see how this principle applies to instance variables. Some of them need to be modifiable and some do
not. You can use the keyword final to specify that a variable is not modifiable (i.e., it’s a constant) and that any
attempt to modify it is an error. For example,
private final int INCREMENT;

Declares a final (constant) instance variable INCREMENT of type int. Such variables can be initialized when
they’re declared. If they are not, they must be initialized in every constructor of the class. Initializing constants
in constructors enables each object of the class to have a different value for the constant. If a final variable is
not initialized in its declaration or in every constructor, a compilation error occurs.

DBU, Department of Electrical and Computer Engineering, 3th Year 17

You might also like