You are on page 1of 170

Chapter 2: Objects and Classes

2.1. Defining a class


2.2. Creating an Object
2.3. Instantiating and using objects
2.3.1. Printing to the Console
2.3.2. Methods and Messages
2.3.3. Parameter Passing
2.3.4. Comparing and Identifying Objects
2.3.5. Destroying Objects
2.3.6. Enumerated Types
2.4. Instance fields
2.5. Constructors and Methods
2.6. Access Modifiers
2.7. Encapsulation

8/15/2023 By: Tadessse Kebede(MSc) 1


2.1. Defining a Class for Objects
▪ Object-oriented programming (OOP) involves programming
using objects.
▪ Class is a collection of objects of similar type.
▪ Classes are user-defined data types & behave like the built-in
types of programming language
▪ Class defines the state and behavior of the basic programming
components known as objects.
▪ A class defines the skeleton of an object.

8/15/2023 By: Tadessse Kebede(MSc) 2


2.1. Defining a Class for 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.
▪ An object has a unique identity, state, and behavior.
o The object identifier is used to define associations between objects and to support retrieval
and comparison of object-oriented data based on the internal identifier rather than the
attribute values of an object.
o The state of an object (also known as its properties or attributes) is represented by data fields
with their current values. A circle object, for example, has a data field radius, which is the
property that characterizes a circle. A rectangle object has data fields width and height, which
are the properties that characterize a rectangle.
o The behavior of an object (also known as its actions) is defined by methods. To invoke a
method on an object is to ask the object to perform an action. For example, you may define a
method named getArea() for circle objects. A circle object may invoke getArea(); to return its
area.

8/15/2023 By: Tadessse Kebede(MSc) 3


2.1. Defining a Class for Objects
▪ Objects of the same type are defined using a common class. A
class is a template, blueprint, or contract that defines what an
object’s data fields and methods will be.
▪ An object is an instance of a class. You can create many
instances of a class.
▪ Creating an instance is referred to as instantiation. The terms
object and instance are often interchangeable.
▪ A Java class uses variables to define data fields and methods
to define actions.
▪ Additionally, a class provides methods of a special type, known
as constructors, which are invoked to create a new object.
▪ A constructor can perform any action, but constructors are designed to
perform initializing actions, such as initializing the data fields of objects.

8/15/2023 By: Tadessse Kebede(MSc) 4


General form of Class
▪ A class is declared by the use of the class keyword.
class classname {//class start
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list){
// body of method
}
type methodname2(parameter-list) {
// body of method
}
//…
type methodnameN(parameter-list) {
// body of method
}
}//class end
8/15/2023 By: Tadessse Kebede(MSc) 5
General form of Class…
▪ The data, or variables, defined within a class are called
instance variables. The code is contained within methods.
▪ Collectively, the methods and variables defined within a class
are called members of the class.
▪ In most classes, the instance variables are acted upon and
accessed by the methods defined for that class.
▪ Variables defined within a class are called instance variables
because each instance of the class (that is, each object of the
class) contains its own copy of these variables.
▪ Thus, the data for one object is separate and unique from the
data for another.
▪ A class called Book includes all its features serving as template
for the concept. Each property is treated as an attribute of that class.
For example, the book’s name, the author’s name, number of pages it
contains are its attributes.
8/15/2023 By: Tadessse Kebede(MSc) 6
Defining a Class for Objects Example
Here is a complete program that uses class Main {
public static void main(String args[]) {
the Box class : Box mybox = new Box();
// A program that uses the Box class double vol;
class Box { // Assign values to mybox's instance variables
String name; mybox.name = “Storage box";
double width; mybox.width = 10;
double height; mybox.height = 20;
double depth; mybox.depth = 15;
// Compute volume of the box
String displayName() { vol = mybox.width * mybox.height * mybox.depth;
return "Name of the book is " + name; System.out.println(mybox.displayName());
} System.out.println("Volume is " + vol);
} }
}

8/15/2023 By: Tadessse Kebede(MSc) 7


Defining a Class for Objects Example…
▪ Apart from defining an object’s structure, a class also defines its
functional interface, known as methods.
▪ Once a Box class is defined, instance of that class can be created and
each instance can have different attributes.
▪ An instance of a class can be used to access the variables and methods
that form part of the class.
▪ The methods in the class operate on individual instance of the class.
▪ As stated, a class defines a new type of data. In this case, the new data
type is called Box. You will use this name to declare objects of type
Box.
▪ Again, 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. Thus every Box object will contain its own copies of the
instance variables name, width, height and depth.
▪ To access these variables, you will use the dot ( . ) operator. The dot
operator links the name of the object with the name of an instance
variable.
8/15/2023 By: Tadessse Kebede(MSc) 8
2.2.Creating an Object
▪ An object in Java is essentially a block of memory that contains
space to store all the instance variables. Creating an object also
known as instantiating an object.
▪ Instantiation is the process of constructing a class object. That’s why an object
is also called the instance of a Java class.
▪ In Java, we can make instances of a class by utilizing the “new” keyword.
▪ The new operator creates an object of the specified class and returns
a reference to that object.
▪ Syntax for object creation:
classname objectname; //declaration
objectname = new classname( ); // instantiation
▪ Example:
Rectangle r1; //declaration
r1= new Rectangle(); //instantiation
//r1 is a reference to Rectangle object
Or
Rectangle r1= new Rectangle(); //declaration & Instantiation in a single line
8/15/2023 By: Tadessse Kebede(MSc) 9
2.2.Creating an Object…
▪ Box bx = new Box(); // create a Box object called bx
▪ After this statement executes, bx will be an instance of Box. Thus, it
will have “physical” reality.
▪ Again, 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.
▪ Thus, every Box object will contain its own copies of the instance
variables width, height, and depth.

8/15/2023 By: Tadessse Kebede(MSc) 10


2.3. Instantiating and using objects
▪ There are three ways to initialize object in Java.
I. By reference variable
II. By method
III. By constructor

8/15/2023 By: Tadessse Kebede(MSc) 11


I. Object and Class Example: Initialization through reference
▪ Initialize the object through a reference variable.
1.class Student{
2. int id;
3. String name;
4.}
5.class TestStudent2{
6. public static void main(String args[]){
7. Student s1=new Student();
8. s1.id=101;
9. s1.name=“Magarsa";
10. System.out.println(s1.id+" "+s1.name);//printing members with a white space
11. }
12.}

Output:
101 Magarsa

8/15/2023 By: Tadessse Kebede(MSc) 12


II. Object and Class Example: Initialization through method
▪ In this example, we are creating the two objects of Student class and initializing the
value to these objects by invoking the insertRecord method. Here, we are displaying the
state (data) of the objects by invoking the displayInformation() method.
1.class Student{
2. int rollno;
3. String name;
4. void insertRecord(int r, String n){
5. rollno=r;
6. name=n;
7. }
8. void displayInformation(){System.out.println(rollno+" "+name);}
9.}
10.class TestStudent4{
11. public static void main(String args[]){
12. Student s1=new Student();
13. Student s2=new Student();
14. s1.insertRecord(111,"Karan");
15. s2.insertRecord(222,"Aryan");
16. s1.displayInformation(); Output:
111 Karan 222 Aryan
17. s2.displayInformation();
8/15/2023 18. } By: Tadessse Kebede(MSc) 13
19.}
III.Object and Class Example: Initialization through a constructor
class Person {
// properties of a person /*
private String name; * Test objects initialization.
private int Age; */
private String gender; public class Sample {
// Constructor : initialize all class fields public static void main(String[] args) {
public Person(String name, int age, String gender) {
this.name = name; Person scott = new Person("Scott", 30, "M");
this.Age = age;
this.gender = gender; System.out.println("Name:" + scott.getName());

} System.out.println("Age: " + scott.getAge());


public String getName() {
return name; System.out.println("Gender:"+scott.getName();
}
public int getAge() { }
return Age;
} }
public String getGender() {
return gender;
}
}

8/15/2023 By: Tadessse Kebede(MSc) 14


2.3. Instantiating and using objects

▪ Example 1: Instantiate a Single Object in


Java: Here, we have a class named
“JavaClass” with variables “x”, “y”, a
user-defined method “Sum()”, and the
predefined “main()” method:
▪ We will create an instance or object of
this class named “jc” in the main()
method by using a “new” keyword.
Using this object, we will access the
“Sum()” method and store the returned
value in the “ans” int type variable.
▪ Lastly, utilize the “System.out.println()”
method to print out the sum at the
console:

8/15/2023 By: Tadessse Kebede(MSc) 15


2.3. Instantiating and using objects

▪ Example 1: Instantiate a Single Object in


Java: Here, we have a class named
“JavaClass” with variables “x”, “y”, a
user-defined method “Sum()”, and the
predefined “main()” method:
▪ We will create an instance or object of
this class named “jc” in the main()
method by using a “new” keyword.
Using this object, we will access the
“Sum()” method and store the returned
value in the “ans” int type variable.
Lastly, utilize the “System.out.println()”
method to print out the sum at the
console:

8/15/2023 By: Tadessse Kebede(MSc) 16


2.3. Instantiating and using objects…

▪ Example 2: Instantiate a Single Object in


Java Using Multiple Classes: In this
example, we have two classes:
“JavaClass1” and “Example”.
▪ “JavaClass1” contains a method named
“Message()” and a String type variable
“name”:
▪ We will create an object of the class
JavaClass1 in the main method of the class
Example and access all the public methods of
the JavaClass1 in the second class named
Example.

▪ Here, we call the method of JavaClass1 in


main method of the Example class by using
object “jc”:
8/15/2023 By: Tadessse Kebede(MSc) 17
2.3. Instantiating and using objects…
▪ Example 3: Instantiate Multiple Objects
in Java Using Multiple Classes:
▪ “Javaclass1” contains a constructor, two
user-defined methods, and two variables.
In the constructor, we will assign the
reference variables to the global
variables of the class. Whereas, the
“Sum()” and the “sub()” methods
returns the sum and differences of the
“x” and “y” variables:
▪ We will create two objects of the
“JavaClass1” as “jc” and “jc1” by passing
integer values as arguments. The constructor
instantiates the class variables with the given
values.
▪ Lastly, we will access all the “Sum()” method
will “jc” object and “sub()” with “jc1”:
8/15/2023 By: Tadessse Kebede(MSc) 18
2.3.1. Accessing Instance Variables
▪ To access instance variables of a class Box {
double width;
class, you will use the dot (.) double height;
operator. double depth;
▪ The dot operator links the name of public static void main(String args[]) {
Box bx1 = new Box();
the object with the name of an Box bx2 = new Box();
instance variable. double vol;
▪ For example, to assign the width bx1.width = 10;
bx1.height = 20;
variable of bx the value 100, you bx1.depth = 15;
would use the following statement: bx2.width = 3;
bx.width = 100; bx2.height = 6;
bx2.depth = 9;
▪ It is important to understand that vol = bx1.width * bx1.height * bx1.depth;
change to the instance variables of System.out.println("Volume is " + vol);
one object has no effect on the vol = bx2.width * bx2.height * bx2.depth;
System.out.println("Volume is " + vol);
instance variables of another. } output
8/15/2023 By: Tadessse Kebede(MSc) } Volume is 3000.0 19
2.3.2. Assigning object reference variables
▪ When you assign one object reference variable to another
object reference variable, you are not creating a copy of the
object, you are only making a copy of the reference.
Box b1 = new Box();
Box b2 = b1;
▪ It simply makes b2 refer to the same object as does b1.

8/15/2023 By: Tadessse Kebede(MSc) 20


2.3.2. Assigning object reference variables…

8/15/2023 By: Tadessse Kebede(MSc) 21


2.3.2. Assigning object reference variables…

8/15/2023 By: Tadessse Kebede(MSc) 22


2.3.2. Assigning object reference variables…
▪ Although b1 and b2 both refer to the same object, they are not
linked in any other way.
▪ For example, a subsequent assignment to b1 will simply undo
b1 from the original object without affecting the object or
affecting b2. For example:
Box b1 = new Box();
Box b3 = new Box();
Box b2 = b1; // ...
b1 = b3;
▪ Here, b1 points the object pointed by b3, but b2 still points to
the previous object.

8/15/2023 By: Tadessse Kebede(MSc) 23


2.3.2. Assigning object reference variables…

8/15/2023 By: Tadessse Kebede(MSc) 24


2.3.2. Assigning object reference variables Code
Example

8/15/2023 By: Tadessse Kebede(MSc) 25


Defining Classes and Creating Objects Example-1
▪ The program constructs three circle objects with radius 1.0, 25, and 125 and
displays the radius and area of each of the three circles. Change the radius of the
second object to 100 and display its new radius and area.
public class TestCircle1 { // Modify circle radius
/** Main method */ circle2.radius = 100;
public static void main(String[] args) { System.out.println("The area of the circle of radius
// Create a circle with radius 1.0 "
Circle1 circle1 = new Circle1(); + circle2.radius + " is " + circle2.getArea());
System.out.println("The area of the circle of radius " }
+ circle1.radius + " is " + circle1.getArea()); }
// Create a circle with radius 25 // Define the circle class with two constructors
Circle1 circle2 = new Circle1(25); class Circle1 {
System.out.println("The area of the circle of radius " double radius;
+ circle2.radius + " is " + circle2.getArea()); /** Construct a circle with radius 1 */
// Create a circle with radius 125 Circle1() {
Circle1 circle3 = new Circle1(125); radius = 1.0;
System.out.println("The area of the circle of radius " }
+ circle2.radius + " is " + circle2.getArea()); /** Construct a circle with a specified radius */
// Create a circle with radius 125 Circle1(double newRadius){
Circle1 circle3 = new Circle1(125); radius = newRadius;
System.out.println("The area of the circle of radius " /** Return the area of this circle */
+ circle3.radius + " is " + circle3.getArea()); double getArea() {
return radius * radius * Math.PI;
}
8/15/2023 By: Tadessse Kebede(MSc) } 26
Defining Classes and Creating Objects Example-2
▪ A program that defines the TV class.

8/15/2023 By: Tadessse Kebede(MSc) 27


Defining Classes and Creating Objects Example-2…
▪ A program that defines the TV class.

8/15/2023 By: Tadessse Kebede(MSc) 28


Defining Classes and Creating Objects Example-2…
▪ A program that defines the TV class.

8/15/2023 By: Tadessse Kebede(MSc) 29


2.3.3. Methods
▪ As mentioned at the beginning of this chapter, classes usually
consist of two things: instance variables and methods.
▪ Methods are functions that operate on instances of classes in
which they are defined.
▪ Objects can communicate with each other using methods and
can call methods in other classes.
▪ Just as there are class and instance variables, there are class
and instance methods .
▪ Instance methods apply and operate on an instance of the class
while class methods operate on the class .

8/15/2023 By: Tadessse Kebede(MSc) 30


Defining Methods
▪ Method definition has four parts: They are, name of the
method, type of object or primitive type the method returns, a
list of parameters and body of the method.
▪ Java permits different methods to have the same name as long
as the argument list is different. This is called method
overloading. A basic method definition resembles the one given
below :
modifier returntype methodname ( type1 arg1, type2 arg2 ) {
// Body of the methods
}
▪ Here, type specifies the type of data returned by the method.
▪ This can be any valid type, including class types that you
create.

8/15/2023 By: Tadessse Kebede(MSc) 31


Defining Methods…
▪ If the method does not return a value, its return type must be
void.
▪ The name of the method is specified by methodname.
▪ Parameter-list is a sequence of type and identifier pairs
separated by commas.
▪ Parameters are essentially variables that receive the value of
the arguments passed to the method when it is called.
▪ If the method has no parameters, then the parameter list will
be empty.

8/15/2023 By: Tadessse Kebede(MSc) 32


Defining Methods 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 method header specifies the modifiers, return value type, method name, and parameters of
the method.

8/15/2023 By: Tadessse Kebede(MSc) 33


Defining Methods Example…
▪ A method may return a value. The returnValueType is the
data type of the value the method returns.
▪ Some methods perform desired operations without returning a
value. In this case, the returnValueType is the keyword void.
For example, the returnValueType is void in the main method,
as well as in System.exit, System.out.println, and
JOptionPane.showMessageDialog.
▪ If a method returns a value, it is called a valuereturning
method, otherwise it is a void method.
▪ The variables defined in the method header are known as
formal parameters or simply parameters.
▪ A parameter is like a placeholder. When a method is invoked,
you pass a value to the parameter.
▪ This value is referred to as an actual parameter or argument.
8/15/2023 By: Tadessse Kebede(MSc) 34
Defining Methods Example
▪ The parameter list refers to the type, order, and number of the
parameters of a method.
▪ The method name and the parameter list together constitute the
method signature.
▪ Parameters are optional; that is, a method may contain no
parameters. For example, the Math.random() method has no
parameters.
▪ The method body contains a collection of statements that define
what the method does.
▪ The method body of the max method uses an if statement to
determine which number is larger and return the value of that
number. In order for a value-returning method to return a result, a
return statement using the keyword return is required.
▪ The method terminates when a return statement is executed.

8/15/2023 By: Tadessse Kebede(MSc) 35


Method Usage
▪ Methods can be used to reduce redundant code and enable code
reuse.
▪ Methods can also be used to modularize code and improve the
quality of the program.
1 public static int sum(int i1, int i2) {
2 int sum = 0;
3 for (int i = i1; i <= i2; i++)
4 sum += i;
5
6 return sum;
7}
8
9 public static void main(String[] args) {
10 System.out.println("Sum from 1 to 10 is " + sum(1, 10));
11 System.out.println("Sum from 20 to 30 is " + sum(20, 30));
12 System.out.println("Sum from 35 to 45 is " + sum(35, 45));
13 }
8/15/2023 By: Tadessse Kebede(MSc) 36
Adding a Method to a Class
▪ Let’s begin by adding a method to the Box class.
▪ It may have occurred to you while looking at the preceding
programs that the computation of a box’s volume was
something that was best handled by the Box .
▪ After all, since the volume of a box is dependent upon the size
of the box, it makes sense to have the Box class compute it.
▪ To do this, you must add a method to Box.

8/15/2023 By: Tadessse Kebede(MSc) 37


Adding a Method to a Class Example
class Box{ public static void main (String args[]) {
double width; Box bx1 = new Box();
double height; Box bx2 = new Box();
double depth; bx1.width=10;
void volume() { bx1.height=20;
System.out.print("Volume is "); bx1.depth=15;
System.out.println(width*height*depth); bx2.width=3;
} bx2.height=6;
bx2.depth=9;
bx1.volume();
bx2.volume();
}
}
output
Volume is 3000.0
8/15/2023 By: Tadessse Kebede(MSc) 38
Volume is 162.0
Set an instance variables values by method
▪ In the preceding examples, the dimensions of each box had to
be set separately by use of a sequence of statements, such as:
bx.width = 10;
bx.height = 20;
bx.depth = 15;
▪ While this code works, it is troubling for two reasons.
▪ First, it is clumsy and error prone. For example, it would be
easy to forget to set a dimension.
▪ Second, in well-designed Java programs, instance variables
should be accessed only through methods defined by their
class.
▪ Thus, a better approach to setting the dimensions of a box is to
create a method that takes the dimension of a box in its
parameters and sets each instance variable appropriately
8/15/2023 By: Tadessse Kebede(MSc) 39
Set an instance variables values by method Example

▪ As you can see, the setDim( )


method is used to set the
dimensions of each box.
▪ For example, when bx.setDim(10,
20, 15); is executed, 10 is copied
into parameter w, 20 is copied
into h, and 15 is copied into d.
▪ Inside setDim( ) the values of w,
h, and d are then assigned to
width, height, and depth,
respectively

8/15/2023 By: Tadessse Kebede(MSc) 40


Calling a Method
▪ In creating a method, you define what the method is to do. To
use a method, you have to call or invoke it. There are two ways
to call a method, depending on whether the method returns a
value or not.
▪ If the method returns a value, a call to the method is usually
treated as a value. For example, int larger = max(3, 4); calls
max(3, 4) and assigns the result of the method to the variable
larger.
▪ Another example of a call that is treated as a value is
System.out.println(max(3, 4)); which prints the return value of
the method call max(3, 4).
▪ 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
8/15/2023 Java!"); By: Tadessse Kebede(MSc) 41
Calling a Method Example

▪ 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. For example, the code
below shows a complete program
that is used to test the max
method.

8/15/2023 By: Tadessse Kebede(MSc) 42


Calling a Method Example….
▪ When the max method is invoked, the flow of control transfers
to it. Once the max method is finished, it returns control back to
the caller.

8/15/2023 By: Tadessse Kebede(MSc) 43


Returning a Value
// Now, volume () returns the volume of a box.
class Box {
▪ In Java, the return keyword returns a double width ;
value from a method. The method will double height;
double depth ;
return the value immediately when the // compute and return volume
keyword is encountered. double volume () {
▪ This means that the method will not return width * height * depth ;
execute any more statements beyond the }
}
return keyword, and any local variables class BoxDemo {
created in the method will be discarded. public static void main ( String args [ ] ) {
▪ As you can see, when volume( ) is called, Box mybox = new Box ( ) ;
it is put on the right side of an double vol;
// Assign values to mybox’s instance variables
assignment statement. On the left is a mybox.width = 10;
variable, in this case vol, that will mybox.height = 20;
receive the value returned by volume( ) . mybox.depth = 15;
// get volume of box
vol = mybox.volume ( ) ;

System.out..println ( “ Volume is “ + vol );


8/15/2023 By: Tadessse Kebede(MSc) } 44
void Method Example 1

▪ The printGrade method is a void


method. It does not return any
value. A call to a void method
must be a statement. So, it is
invoked as a statement in line 4 in
the main method.
▪ Like any Java statement, it is
terminated with a semicolon.

8/15/2023 By: Tadessse Kebede(MSc) 45


void Method Example 2

▪ To see the differences between a void


and a value-returning method, let us
redesign the printGrade method to
return a value.
▪ The getGrade method defined in lines 7–
18 returns a character grade based on
the numeric score value. The caller
invokes this method in lines 3–4.
▪ The getGrade method can be invoked by
a caller wherever a character may
appear.
▪ The printGrade method does not return
any value. It must be also invoked as a
statement.

8/15/2023 By: Tadessse Kebede(MSc) 46


2.3.4. Parameter Passing…
▪ The parameter is a variable in the method with its own
memory space. The variable is allocated when the method is
invoked, and it disappears when the method is returned to its
caller.
▪ Parameters allow a method to be generalized. That is, a
parameterized method can operate on a variety of data and/or
be used in a number of slightly different situations.
▪ To illustrate this point, let’s use a very simple example.
▪ Here is a method that returns the square of the number 10:
int square()
{
return 10 * 10;
}
▪ While this method does, indeed, return the value of 10
squared, its use is very limited.
8/15/2023 By: Tadessse Kebede(MSc) 47
2.3.4. Parameter Passing
▪ However, if you modify the method so that it takes a
parameter, as shown next, then you can make square( ) much
more useful.
int square(int i)
{
return i * i;
}
▪ Now, square( ) will return the square of whatever value it is
called with.
▪ That is, square( ) is now a general-purpose method that can
compute the square of any integer value, rather than just 10.

8/15/2023 By: Tadessse Kebede(MSc) 48


2.3.4. Parameter Passing
▪ Here is an example:
int x, y;
x = square(5); // x equals 25
x = square(9); // x equals 81
y = 2;
x = square(y); // x equals 4
▪ In the first call to square( ), the value 5 will be passed into
parameter i.
▪ In the second call, i will receive the value 9.
▪ The third invocation passes the value of y, which is 2 in this
example.
▪ As these examples show, square( ) is able to return the square
of whatever data it is passed

8/15/2023 By: Tadessse Kebede(MSc) 49


2.3.4. Parameter Passing
▪ It is important to keep the two terms parameter and argument
straight.
▪ A parameter is a variable defined by a method that receives a
value when the method is called.
▪ For example, in square ( ), i is a parameter.
▪ An argument is a value that is passed to a method when it is
invoked.
▪ For example: square (100) passes 100 as an argument.
▪ Inside square( ), the parameter i receives that value.

8/15/2023 By: Tadessse Kebede(MSc) 50


2.3.5. Passing arguments
▪ There are two ways that a computer language can pass an
argument to a subroutine.(passing by value and passing by
reference).
▪ Passing by- value -This method copies the value of an
argument into the formal parameter of the subroutine.
▪ Therefore, changes made to the parameter variable values
have no effect on the argument variable values.
▪ Used to pass simple data types.(primitive data type)
▪ Passing by reference -In this method, a reference to an
argument (not the value of the argument) is passed to the
parameter.
▪ Changes made to the parameter variable values will affect the
argument variable values.
▪ Used to pass objects.
8/15/2023 By: Tadessse Kebede(MSc) 51
Passing arguments by Values
▪ 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.

8/15/2023 By: Tadessse Kebede(MSc) 52


Passing by Values…
▪ Here, the value of x (1) is passed to the parameter n to invoke the
increment method (line 5). n is incremented by 1 in the method (line 10),
but x is not changed no matter what the method does.
1 public class Increment {
2 public static void main(String[] args) {
3 int x = 1;
4 System.out.println("Before the call, x is " + x);
5 increment(x); //invoke increment
6 System.out.println("after the call, x is " + x);
7}
8
9 public static void increment(int n) {
10 n++;
11 System.out.println("n inside the method is " + n);
12 }
13 }

8/15/2023 By: Tadessse Kebede(MSc) 53


Passing arguments by reference Example
▪ Java is Pass by Value, Not Pass by Reference
public class ByRference {
int a,b;
ByRference(int j,int i) {
a=j;
b=i;
}
void Test(ByRference ref) {
ref.a=ref.a*2;
ref.b=ref.b/2;
}
public static void main(String[] args) {
ByRference reff=new ByRference(15,20);
System.out.println(reff.a+" "+reff.b);
reff.Test(reff);
System.out.println(reff.a+" "+reff.b);
}
}
output:
8/15/2023 15, 20 By: Tadessse Kebede(MSc) 54
30,10
2.3.6. Comparing and Identifying Objects
▪ Comparing objects is a little different than comparing
primitive typed values like numbers.
▪ Objects can be very complex and have many attribute values or
instance variables inside them.
▪ Java provides the two methods of the Object class to compare
the objects are as follows:
o Java equals() Method
o Java hashCode() Method

8/15/2023 By: Tadessse Kebede(MSc) 55


Java equals() Method
▪ In Java, the == operator compares that two references are
identical or not. Whereas the equals() method compares two
objects.
▪ The == comparison operator is designed to compare the value
of two variables. Since the value that is stored for a reference
variable is the memory location, using == will return whether
or not the two objects have the same reference. When two
objects have the same reference, they are said to be aliases.
▪ Objects are equal when they have the same state (usually
comparing variables). Objects are identical when they share
the class identity.
▪ For example, the expression obj1==obj2 tests the identity, not
equality. While the expression obj1.equals(obj2) compares
equality.
8/15/2023 By: Tadessse Kebede(MSc) 56
Java equals() Method
▪ In Java, the method that is used is called .equals(). This
method is called from a variable and it passes a parameter to
compare to in order to determine if the values are equal.
▪ If you assume that one rectangle equals another rectangle if
they have the same width and height, then .equals() can return
true if the method compares the width and height of two
rectangles and finds them to be the same.
▪ Take a look at the example below:
Rectangle one = new Rectangle(3,7);
Rectangle two = new Rectangle(3,7);
boolean isAlias = one == two; // Will be set to false
boolean isEqual = one.equals(two); // Will be set to true

8/15/2023 By: Tadessse Kebede(MSc) 57


Java hashCode() Method
▪ In Java, hash code is a 32-bit signed integer value.
▪ It is a unique id provided by JVM to Java object.
▪ Each Java object is associated with the hash code.
▪ The hash code is managed by a hash-based data structure,
such as HashTable, HashSet, etc.
▪ Syntax: public int hashCode()
▪ It returns a randomly generated hash code value of the object
that is unique for each instance. The randomly generated
value might change during the several executions of the
program.
▪ When it is invoked more than once during the execution of an
application, the hashCode() method will consistently return
the same hash code (integer value). Note that the object should
not be modified.
8/15/2023 By: Tadessse Kebede(MSc) 58
Java hashCode() Method Example
1.public class Employee 1.public class HashcodeExample
2.{ 2.{
3.private int regno; 3.public static void main(String[] args)
4.private String name; 4.{
5.//constructor of Employee class 5.//creating two instances of the Employee class
6.public Employee(int regno, String name) 6.Employee emp1 = new Employee(918, "Maria");
7.{ 7.Employee emp2 = new Employee(918, "Maria");
8.this.name = name; 8.//invoking hashCode() method
9.this.regno = regno; 9.int a=emp1.hashCode();
10.} 10.int b=emp2.hashCode();
11.public int getRegno() 11.System.out.println("hashcode of emp1 = " + a);
12.{ 12.System.out.println("hashcode of emp2 = " + b);
13.return regno; 13.System.out.println("Comparing objects emp1 and emp2 = " + emp1.equals(emp2));
14.}
15.public void setRegno(int Regno) 14.}
16.{ 15.}
17.this.regno = regno;
18.} Output:
19.public String getName() hashcode of emp1 = 2032578917
20.{ hashcode of emp2 = 1531485190
21.return name; Comparing objects emp1 and emp2 = true
22.}
23.public void setName(String name)
24.{
25.this.name = name;
8/15/2023 26.}
By: Tadessse Kebede(MSc) 59
2.3.7. Destroying Objects or Garbage Collection
▪ In Java, objects are automatically destroyed through a process called
garbage collection.
▪ Garbage collection is responsible for reclaiming memory occupied by objects
that are no longer accessible.
▪ When there are no references to an object, it becomes eligible for garbage
collection.
▪ Java's garbage collection eliminates many common programming errors
like dangling pointers and memory leaks.
▪ Garbage collection is handled by the system, relieving programmers from
managing memory explicitly.
▪ Garbage collector calls finalize() method for clean up activity before
destroying the object.
▪ The garbage collector in Java can be called explicitly using the following
method: System.gc();
▪ System.gc() is a method in Java that invokes garbage collector which will
destroy the unreferenced objects. System.gc() calls finalize() method only
once for each object.
8/15/2023 By: Tadessse Kebede(MSc) 60
2.3.7. Destroying Objects or Garbage Collection…
▪ Consider the following two statements (though in reality, you’d
never do anything like this):
Student std = new Student(" John Smith ");
std = null;
▪ In the first line, a reference to a newly created Student object is stored in
the variable std.
▪ But in the next line, the value of std is changed, and the reference to the
Student object is gone.
▪ In fact, there are now no references whatsoever to that object stored in any
variable.
▪ So there is no way for the program ever to use the object again. It might as
well not exist.
▪ In fact, the memory occupied by the object should be reclaimed to be used
for another purpose.
▪ Hence, it is eligible for garbage collection. The garbage collector
calls finalize() method to perform clean-up before destroying the object
8/15/2023 By: Tadessse Kebede(MSc) 61
2.3.8. Enumerated Types
▪ An enum is a special "class" that represents a group of
constants (unchangeable variables, like final variables).
▪ To create an enum, use the enum keyword (instead of class or
interface), and separate the constants with a comma.
▪ You can access enum constants with the dot syntax:
▪ Note that they should be in uppercase letters:
enum Level {
LOW,
MEDIUM,
HIGH
}
public class Main {
public static void main(String[] args) {
Level myVar = Level.MEDIUM;
System.out.println(myVar);
}
}
8/15/2023 By: Tadessse Kebede(MSc) 62
2.4. Instance fields
▪ Java lets you declare two types of fields for a class:
• Class fields
• Instance fields
▪ Class fields are class variables and Instance fields are instance variables.
▪ A class variable is also known as a static variable. an instance variable is
also known as a non-static variable.
▪ All class variables must be declared using the static keyword as a modifier.
▪ Difference: Class field only have one instance while the instance field can
have as many instances as you create.
▪ Declaration of a Employee Class with One Class Variable and Two Instance
Variables
class Employee {
String name; // An instance variable
String gender; // An instance variable
static long count; // A class variable because of the static modifier
}

8/15/2023 By: Tadessse Kebede(MSc) 63


Instance fields Example
public class VariableExample{
int myVariable;
static int data = 30;

public static void main(String args[]){


int a = 100;
VariableExample obj = new VariableExample();

System.out.println("Value of instance variable myVariable: "+obj.myVariable);


System.out.println("Value of static variable data: "+VariableExample.data);
System.out.println("Value of local variable a: "+a);
}
}
Output
Value of instance variable myVariable: 0
Value of static variable data: 30
Value of local variable a: 100

8/15/2023 By: Tadessse Kebede(MSc) 64


2.5. Constructors
▪ It can be tedious to initialize all of the variables in a class each
time an instance is created.
▪ It is possible to initialize objects they are created by:
• Using the dot operator
• The help of methods
▪ But it would be simpler and more concise to initialize an object
when it is first created.
▪ Java supports a special type of method, called a constructor,
that enables an object to initialize itself when it is created.
▪ Constructors are special methods that are used to construct an
instance of a class.
▪ A constructor initializes an object immediately upon creation.
▪ Call the constructor(s) preceding it with the new keyword.

8/15/2023 By: Tadessse Kebede(MSc) 65


Rules with constructors
▪ The definition of a constructor looks much like the definition of
any other method, with three differences.
1. A constructor does not have any return type (not even void).
2. The name of the constructor must be the same as the name of the class
in which it is defined.
3. The only modifiers that can be used on a constructor definition are the
access modifiers public, private, and protected. (In particular, a
constructor can’t be declared static, abstract , final , native , static , or
synchronized.)
Constructor Normal method
Has no return type Has return type
Its name should the Its name can be any
same as class name identifier
Invoked with new Can be invoked without
keyword. new keyword.

8/15/2023 By: Tadessse Kebede(MSc) 66


Types of constructor
1. Default constructor: is a constructor which receives no
arguments.
• has no parameters
• Default parameters defined automatically (if there is no
parameterized constructor)
• Default parameters defined by the programmer.
2. Parameterized Constructor:- is a constructor which can receives
one or more arguments.
• has one or more parameters
• When an instance of an object is created then the instance
will call the constructor.
• It will be called based on the types of constructor that has
been called while object is created.

8/15/2023 By: Tadessse Kebede(MSc) 67


Default of constructor Example
Class employee{
employee() //default constructor
{
System.out.println(“Hello”);
}
public static void main(String args[]) {
Employee emp = new employee();
}
}
Output
Hello

8/15/2023 By: Tadessse Kebede(MSc) 68


Parameterized constructor Example
class employee{
String Ename;
float salary;
employee(String name, float sal) //parameterized constructor
{
Ename= name;
salary = sal;
System.out.println(Ename +”\t”+ salary);
}
public static void main(String args[]) {
Employee emp = new employee(“Teborne”,4500.00);
}
}
Output
=====
Teborne 4500.00
8/15/2023 By: Tadessse Kebede(MSc) 69
Overloaded constructor
▪ Constructor with the same name, but the compiler uses two mechanism to
differentiate the overloaded constructors.
• number of parameter
• data type of parameter
public class students{
String name;
students() {
System.out.println(“default constructor”);
}
students(String name) {
this.name=name;
System.out.println(this.name);
}
public static void main(String[] args){
students stud1=new students();
students stud2=new students(“Teborne”);
}
}
Output
default constructor
Teborne
8/15/2023 By: Tadessse Kebede(MSc) 70
“This” keyword
▪ this -> implicit reference to current object.
▪ Allow us to use the same identifier for instance variable and local variable
▪ To prevent instance variables hiding by local variable
▪ The this keyword refers to the current object in a method or constructor.
▪ used to:
✓ prevent instance variables hiding by local variable.
✓ improve readability of the program
✓ invoke the constructor.

class students{
String name;
students(String name)
{
this.name=name;
}
}

8/15/2023 By: Tadessse Kebede(MSc) 71


Using objects as parameter
public class Boxx {
double wid,het,dep;
Boxx() {
}
Boxx(Boxx bx) { //Using object as parameter
wid=bx.wid;
het=bx.het;
dep=bx.dep;
System.out.println(wid*het*dep);
}
public static void main(String[] args){
Boxx b=new Boxx();
b.wid=10;
b.het=20;
b.dep=15;
Boxx bb=new Boxx(b);
}
}
Output
3000

8/15/2023 By: Tadessse Kebede(MSc) 72


Returning objects
public class Rectangle {
int len,wid;
Rectangle(int l, int w)
{
len=l;
wid=w;
}
Rectangle getRectangle()
{
Rectangle rect=new Rectangle(10,20);
return rect; //returning object
}
public static void main(String[] args) {
Rectangle r=new Rectangle(40, 50);
Rectangle r2;
r2=r.getRectangle();
System.out.println(r.len+" "+r.wid);
System.out.println(r2.len+" "+r2.wid);
}
}
Output
40 50
8/15/2023 10 20 By: Tadessse Kebede(MSc) 73
2.6. Access Modifiers
▪ The access modifiers in Java specifies the accessibility or scope
of a field, method, constructor, or class.
▪ We can change the access level of fields, constructors, methods,
and class by applying the access modifier on it.
▪ There are four types of Java access modifiers:
• Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
• Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.
• Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
• Public: The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside the
package.
8/15/2023 By: Tadessse Kebede(MSc) 74
Private access modifier
▪ In this example, we have created two classes A and Simple. A class
contains private data member and private method. We are accessing
these private members from outside the class, so there is a compile-time
error.
1.class A{
2.private int data=40;
3.private void msg(){
4.System.out.println("Hello java");
5.}
6.}
7.
8.public class Simple{
9. public static void main(String args[]){
10. A obj=new A();
11. System.out.println(obj.data);//Compile Time Error
12. obj.msg();//Compile Time Error
8/15/2023
13. } By: Tadessse Kebede(MSc) 75
14.}
Role of Private Constructor
▪ If you make any class constructor private, you cannot create the instance
of that class from outside the class. For example:
1.class A{
2.private A(){}//private constructor
3.void msg(){System.out.println("Hello java");}
4.}
5.public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9.}

8/15/2023 By: Tadessse Kebede(MSc) 76


Default Modifiers
▪ If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within
package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is
more restrictive than protected, and public.
▪ Example of default access modifier
▪ In this example, we have created two packages pack and mypack. We are accessing the A class from outside
its package, since A class is not public, so it cannot be accessed from outside the package.
1.//save by A.java
2.package pack;
3.class A{
4. void msg(){System.out.println("Hello");}
5.}
6.//save by B.java
7.package mypack;
8.import pack.*;
9.class B{
10. public static void main(String args[]){
11. A obj = new A();//Compile Time Error
12. obj.msg();//Compile Time Error
13. }
14.}
▪ In the above example, the scope of class A and its method msg() is default so it cannot be accessed from
outside the package.

8/15/2023 By: Tadessse Kebede(MSc) 77


Protected access modifier
▪ The protected access modifier is accessible within package and outside the package but
through inheritance only.
▪ The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
▪ It provides more accessibility than the default modifier.
▪ Example of protected access modifier
▪ In this example, we have created the two packages pack and mypack. The A class of pack package
is public, so can be accessed from outside the package. But msg method of this package is
declared as protected, so it can be accessed from outside the class only through inheritance.
1.//save by A.java
2.package pack;
3.public class A{
4.protected void msg(){System.out.println("Hello");}
5.}
1.//save by B.java
2.package mypack;
3.import pack.*;
4.
5.class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10.}
Output:
8/15/2023 Hello
By: Tadessse Kebede(MSc) 78
Public access modifier
▪ The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.
Example of public access modifier
1.//save by A.java
2.
3.package pack;
4.public class A{
5.public void msg(){System.out.println("Hello");}
6.}
1.//save by B.java
2.
3.package mypack;
4.import pack.*;
5.
6.class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11.}
Output:Hello

8/15/2023 By: Tadessse Kebede(MSc) 79


2.7. Encapsulation
▪ Encapsulation in Java is a process of wrapping code and data
together into a single unit, for example, a capsule which is mixed of
several medicines.
▪ We can create a fully encapsulated class in Java by making all the
data members of the class private.
▪ Now we can use setter and getter methods to set and get the data in
it.
▪ To prevent direct modifications of data fields, you should declare the
data fields private, using the private modifier.
▪ This is known as data field encapsulation.
▪ A private data field cannot be accessed by an object from outside the
class that defines the private field. But often a client needs to
retrieve and modify a data field. To make a private data field
accessible, provide a get method to return its value.
▪ To enable a private data field to be updated, provide a set method to
set a new value.
8/15/2023 By: Tadessse Kebede(MSc) 80
2.7. Encapsulation…
▪ In encapsulation the variables of a class will be hidden from
other classes, and can be accessed only through the methods of
their current class, therefore it is also known as data hiding.
▪ To achieve encapsulation in Java:
• Declare the variables and methods of a class as private.
• Provide public setter and getter methods to access and
modify the variables values.
▪ setter and getter: setter method used to set/initialize instance
variables, and getter method used to accept the instance
variable value that has been set by the setter method
▪ Example: if the instance variable is name:
✓ setter method = setName(param),
✓ getter method =getName()

8/15/2023 By: Tadessse Kebede(MSc) 81


2.7. Encapsulation…
▪ A get method has the following signature:
public returnType getPropertyName()
▪ If the returnType is boolean, the get method should be defined
as follows by convention:
public boolean isPropertyName()
▪ A set method has the following signature:
public void setPropertyName(dataType propertyValue)

8/15/2023 By: Tadessse Kebede(MSc) 82


Advantage of Encapsulation in Java
▪ By providing only a setter or getter method, you can make the
class read-only or write-only. In other words, you can skip the
getter or setter methods.
▪ It provides you the control over the data. Suppose you want to
set the value of id which should be greater than 100 only, you
can write the logic inside the setter method. You can write the
logic not to store the negative numbers in the setter methods.
▪ It is a way to achieve data hiding in Java because other class
will not be able to access the data through the private data
members.
▪ The encapsulate class is easy to test. So, it is better for unit
testing.

8/15/2023 By: Tadessse Kebede(MSc) 83


Encapsulation Example
1.//A Account class which is a fully encapsulated class. 23. public void setEmail(String email) {
2.//It has a private data member and getter and setter 24. this.email = email;
25. }
methods.
26. public float getAmount() {
3.class Account { 27. return amount;
4.//private data members 28. }
5.private long acc_no; 29. public void setAmount(float amount) {
6.private String name,email; 30. this.amount = amount;
7.private float amount; 31. }
8.//public getter and setter methods 33. }
1.//A Java class to test the encapsulated class Account.
9.public long getAcc_no() {
2.public class TestEncapsulation {
10. return acc_no; 3.public static void main(String[] args) {
11.} 4. //creating instance of Account class
12.public void setAcc_no(long acc_no) { 5. Account acc=new Account();
13. this.acc_no = acc_no; 6. //setting values through setter methods
14.} 7. acc.setAcc_no(1000234567);
15.public String getName() { 8. acc.setName(“John Marsil");
9. acc.setEmail(“marsil@gamil.com");
16. return name;
10. acc.setAmount(2000ETB);
17.} 11. //getting values through getter methods
18.public void setName(String name) { 12. System.out.println(acc.getAcc_no()+" "+acc.getName()+"
19. this.name = name; "+acc.getEmail()+" "+acc.getAmount());
20.} 13.}
21.public String getEmail() { 14.}
8/15/2023 22. return email; By: Tadessse Kebede(MSc) 84
End-of-Chapter-2

8/15/2023 By: Tadessse Kebede(MSc) 85


Chapter 2: Objects and Classes
2.1. Defining a class
2.2. Creating an Object
2.3. Instantiating and using objects
2.3.1. Printing to the Console
2.3.2. Methods and Messages
2.3.3. Parameter Passing
2.3.4. Comparing and Identifying Objects
2.3.5. Destroying Objects
2.3.6. Enumerated Types
2.4. Instance fields
2.5. Constructors and Methods
2.6. Access Modifiers
2.7. Encapsulation

8/15/2023 By: Tadessse Kebede(MSc) 86


2.1. Defining a Class for Objects
▪ Object-oriented programming (OOP) involves programming
using objects.
▪ Class is a collection of objects of similar type.
▪ Classes are user-defined data types & behave like the built-in
types of programming language
▪ Class defines the state and behavior of the basic programming
components known as objects.
▪ A class defines the skeleton of an object.

8/15/2023 By: Tadessse Kebede(MSc) 87


2.1. Defining a Class for 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.
▪ An object has a unique identity, state, and behavior.
o The object identifier is used to define associations between objects and to support retrieval
and comparison of object-oriented data based on the internal identifier rather than the
attribute values of an object.
o The state of an object (also known as its properties or attributes) is represented by data fields
with their current values. A circle object, for example, has a data field radius, which is the
property that characterizes a circle. A rectangle object has data fields width and height, which
are the properties that characterize a rectangle.
o The behavior of an object (also known as its actions) is defined by methods. To invoke a
method on an object is to ask the object to perform an action. For example, you may define a
method named getArea() for circle objects. A circle object may invoke getArea(); to return its
area.

8/15/2023 By: Tadessse Kebede(MSc) 88


2.1. Defining a Class for Objects
▪ Objects of the same type are defined using a common class. A
class is a template, blueprint, or contract that defines what an
object’s data fields and methods will be.
▪ An object is an instance of a class. You can create many
instances of a class.
▪ Creating an instance is referred to as instantiation. The terms
object and instance are often interchangeable.
▪ A Java class uses variables to define data fields and methods
to define actions.
▪ Additionally, a class provides methods of a special type, known
as constructors, which are invoked to create a new object.
▪ A constructor can perform any action, but constructors are designed to
perform initializing actions, such as initializing the data fields of objects.

8/15/2023 By: Tadessse Kebede(MSc) 89


General form of Class
▪ A class is declared by the use of the class keyword.
class classname {//class start
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list){
// body of method
}
type methodname2(parameter-list) {
// body of method
}
//…
type methodnameN(parameter-list) {
// body of method
}
}//class end
8/15/2023 By: Tadessse Kebede(MSc) 90
General form of Class…
▪ The data, or variables, defined within a class are called
instance variables. The code is contained within methods.
▪ Collectively, the methods and variables defined within a class
are called members of the class.
▪ In most classes, the instance variables are acted upon and
accessed by the methods defined for that class.
▪ Variables defined within a class are called instance variables
because each instance of the class (that is, each object of the
class) contains its own copy of these variables.
▪ Thus, the data for one object is separate and unique from the
data for another.
▪ A class called Book includes all its features serving as template
for the concept. Each property is treated as an attribute of that class.
For example, the book’s name, the author’s name, number of pages it
contains are its attributes.
8/15/2023 By: Tadessse Kebede(MSc) 91
Defining a Class for Objects Example
Here is a complete program that uses class Main {
public static void main(String args[]) {
the Box class : Box mybox = new Box();
// A program that uses the Box class double vol;
class Box { // Assign values to mybox's instance variables
String name; mybox.name = “Storage box";
double width; mybox.width = 10;
double height; mybox.height = 20;
double depth; mybox.depth = 15;
// Compute volume of the box
String displayName() { vol = mybox.width * mybox.height * mybox.depth;
return "Name of the book is " + name; System.out.println(mybox.displayName());
} System.out.println("Volume is " + vol);
} }
}

8/15/2023 By: Tadessse Kebede(MSc) 92


Defining a Class for Objects Example…
▪ Apart from defining an object’s structure, a class also defines its
functional interface, known as methods.
▪ Once a Box class is defined, instance of that class can be created and
each instance can have different attributes.
▪ An instance of a class can be used to access the variables and methods
that form part of the class.
▪ The methods in the class operate on individual instance of the class.
▪ As stated, a class defines a new type of data. In this case, the new data
type is called Box. You will use this name to declare objects of type
Box.
▪ Again, 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. Thus every Box object will contain its own copies of the
instance variables name, width, height and depth.
▪ To access these variables, you will use the dot ( . ) operator. The dot
operator links the name of the object with the name of an instance
variable.
8/15/2023 By: Tadessse Kebede(MSc) 93
2.2.Creating an Object
▪ An object in Java is essentially a block of memory that contains
space to store all the instance variables. Creating an object also
known as instantiating an object.
▪ Instantiation is the process of constructing a class object. That’s why an object
is also called the instance of a Java class.
▪ In Java, we can make instances of a class by utilizing the “new” keyword.
▪ The new operator creates an object of the specified class and returns
a reference to that object.
▪ Syntax for object creation:
classname objectname; //declaration
objectname = new classname( ); // instantiation
▪ Example:
Rectangle r1; //declaration
r1= new Rectangle(); //instantiation
//r1 is a reference to Rectangle object
Or
Rectangle r1= new Rectangle(); //declaration & Instantiation in a single line
8/15/2023 By: Tadessse Kebede(MSc) 94
2.2.Creating an Object…
▪ Box bx = new Box(); // create a Box object called bx
▪ After this statement executes, bx will be an instance of Box. Thus, it
will have “physical” reality.
▪ Again, 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.
▪ Thus, every Box object will contain its own copies of the instance
variables width, height, and depth.

8/15/2023 By: Tadessse Kebede(MSc) 95


2.3. Instantiating and using objects
▪ There are three ways to initialize object in Java.
I. By reference variable
II. By method
III. By constructor

8/15/2023 By: Tadessse Kebede(MSc) 96


I. Object and Class Example: Initialization through reference
▪ Initialize the object through a reference variable.
1.class Student{
2. int id;
3. String name;
4.}
5.class TestStudent2{
6. public static void main(String args[]){
7. Student s1=new Student();
8. s1.id=101;
9. s1.name=“Magarsa";
10. System.out.println(s1.id+" "+s1.name);//printing members with a white space
11. }
12.}

Output:
101 Magarsa

8/15/2023 By: Tadessse Kebede(MSc) 97


II. Object and Class Example: Initialization through method
▪ In this example, we are creating the two objects of Student class and initializing the
value to these objects by invoking the insertRecord method. Here, we are displaying the
state (data) of the objects by invoking the displayInformation() method.
1.class Student{
2. int rollno;
3. String name;
4. void insertRecord(int r, String n){
5. rollno=r;
6. name=n;
7. }
8. void displayInformation(){System.out.println(rollno+" "+name);}
9.}
10.class TestStudent4{
11. public static void main(String args[]){
12. Student s1=new Student();
13. Student s2=new Student();
14. s1.insertRecord(111,"Karan");
15. s2.insertRecord(222,"Aryan");
16. s1.displayInformation(); Output:
111 Karan 222 Aryan
17. s2.displayInformation();
8/15/2023 18. } By: Tadessse Kebede(MSc) 98
19.}
III.Object and Class Example: Initialization through a constructor
class Person {
// properties of a person /*
private String name; * Test objects initialization.
private int Age; */
private String gender; public class Sample {
// Constructor : initialize all class fields public static void main(String[] args) {
public Person(String name, int age, String gender) {
this.name = name; Person scott = new Person("Scott", 30, "M");
this.Age = age;
this.gender = gender; System.out.println("Name:" + scott.getName());

} System.out.println("Age: " + scott.getAge());


public String getName() {
return name; System.out.println("Gender:"+scott.getName();
}
public int getAge() { }
return Age;
} }
public String getGender() {
return gender;
}
}

8/15/2023 By: Tadessse Kebede(MSc) 99


2.3. Instantiating and using objects

▪ Example 1: Instantiate a Single Object in


Java: Here, we have a class named
“JavaClass” with variables “x”, “y”, a
user-defined method “Sum()”, and the
predefined “main()” method:
▪ We will create an instance or object of
this class named “jc” in the main()
method by using a “new” keyword.
Using this object, we will access the
“Sum()” method and store the returned
value in the “ans” int type variable.
▪ Lastly, utilize the “System.out.println()”
method to print out the sum at the
console:

8/15/2023 By: Tadessse Kebede(MSc) 100


2.3. Instantiating and using objects

▪ Example 1: Instantiate a Single Object in


Java: Here, we have a class named
“JavaClass” with variables “x”, “y”, a
user-defined method “Sum()”, and the
predefined “main()” method:
▪ We will create an instance or object of
this class named “jc” in the main()
method by using a “new” keyword.
Using this object, we will access the
“Sum()” method and store the returned
value in the “ans” int type variable.
Lastly, utilize the “System.out.println()”
method to print out the sum at the
console:

8/15/2023 By: Tadessse Kebede(MSc) 101


2.3. Instantiating and using objects…

▪ Example 2: Instantiate a Single Object in


Java Using Multiple Classes: In this
example, we have two classes:
“JavaClass1” and “Example”.
▪ “JavaClass1” contains a method named
“Message()” and a String type variable
“name”:
▪ We will create an object of the class
JavaClass1 in the main method of the class
Example and access all the public methods of
the JavaClass1 in the second class named
Example.

▪ Here, we call the method of JavaClass1 in


main method of the Example class by using
object “jc”:
8/15/2023 By: Tadessse Kebede(MSc) 102
2.3. Instantiating and using objects…
▪ Example 3: Instantiate Multiple Objects
in Java Using Multiple Classes:
▪ “Javaclass1” contains a constructor, two
user-defined methods, and two variables.
In the constructor, we will assign the
reference variables to the global
variables of the class. Whereas, the
“Sum()” and the “sub()” methods
returns the sum and differences of the
“x” and “y” variables:
▪ We will create two objects of the
“JavaClass1” as “jc” and “jc1” by passing
integer values as arguments. The constructor
instantiates the class variables with the given
values.
▪ Lastly, we will access all the “Sum()” method
will “jc” object and “sub()” with “jc1”:
8/15/2023 By: Tadessse Kebede(MSc) 103
2.3.1. Accessing Instance Variables
▪ To access instance variables of a class Box {
double width;
class, you will use the dot (.) double height;
operator. double depth;
▪ The dot operator links the name of public static void main(String args[]) {
Box bx1 = new Box();
the object with the name of an Box bx2 = new Box();
instance variable. double vol;
▪ For example, to assign the width bx1.width = 10;
bx1.height = 20;
variable of bx the value 100, you bx1.depth = 15;
would use the following statement: bx2.width = 3;
bx.width = 100; bx2.height = 6;
bx2.depth = 9;
▪ It is important to understand that vol = bx1.width * bx1.height * bx1.depth;
change to the instance variables of System.out.println("Volume is " + vol);
one object has no effect on the vol = bx2.width * bx2.height * bx2.depth;
System.out.println("Volume is " + vol);
instance variables of another. } output
8/15/2023 By: Tadessse Kebede(MSc) } Volume is 3000.0 104
2.3.2. Assigning object reference variables
▪ When you assign one object reference variable to another
object reference variable, you are not creating a copy of the
object, you are only making a copy of the reference.
Box b1 = new Box();
Box b2 = b1;
▪ It simply makes b2 refer to the same object as does b1.

8/15/2023 By: Tadessse Kebede(MSc) 105


2.3.2. Assigning object reference variables…

8/15/2023 By: Tadessse Kebede(MSc) 106


2.3.2. Assigning object reference variables…

8/15/2023 By: Tadessse Kebede(MSc) 107


2.3.2. Assigning object reference variables…
▪ Although b1 and b2 both refer to the same object, they are not
linked in any other way.
▪ For example, a subsequent assignment to b1 will simply undo
b1 from the original object without affecting the object or
affecting b2. For example:
Box b1 = new Box();
Box b3 = new Box();
Box b2 = b1; // ...
b1 = b3;
▪ Here, b1 points the object pointed by b3, but b2 still points to
the previous object.

8/15/2023 By: Tadessse Kebede(MSc) 108


2.3.2. Assigning object reference variables…

8/15/2023 By: Tadessse Kebede(MSc) 109


2.3.2. Assigning object reference variables Code
Example

8/15/2023 By: Tadessse Kebede(MSc) 110


Defining Classes and Creating Objects Example-1
▪ The program constructs three circle objects with radius 1.0, 25, and 125 and
displays the radius and area of each of the three circles. Change the radius of the
second object to 100 and display its new radius and area.
public class TestCircle1 { // Modify circle radius
/** Main method */ circle2.radius = 100;
public static void main(String[] args) { System.out.println("The area of the circle of radius
// Create a circle with radius 1.0 "
Circle1 circle1 = new Circle1(); + circle2.radius + " is " + circle2.getArea());
System.out.println("The area of the circle of radius " }
+ circle1.radius + " is " + circle1.getArea()); }
// Create a circle with radius 25 // Define the circle class with two constructors
Circle1 circle2 = new Circle1(25); class Circle1 {
System.out.println("The area of the circle of radius " double radius;
+ circle2.radius + " is " + circle2.getArea()); /** Construct a circle with radius 1 */
// Create a circle with radius 125 Circle1() {
Circle1 circle3 = new Circle1(125); radius = 1.0;
System.out.println("The area of the circle of radius " }
+ circle2.radius + " is " + circle2.getArea()); /** Construct a circle with a specified radius */
// Create a circle with radius 125 Circle1(double newRadius){
Circle1 circle3 = new Circle1(125); radius = newRadius;
System.out.println("The area of the circle of radius " /** Return the area of this circle */
+ circle3.radius + " is " + circle3.getArea()); double getArea() {
return radius * radius * Math.PI;
}
8/15/2023 By: Tadessse Kebede(MSc) } 111
Defining Classes and Creating Objects Example-2
▪ A program that defines the TV class.

8/15/2023 By: Tadessse Kebede(MSc) 112


Defining Classes and Creating Objects Example-2…
▪ A program that defines the TV class.

8/15/2023 By: Tadessse Kebede(MSc) 113


Defining Classes and Creating Objects Example-2…
▪ A program that defines the TV class.

8/15/2023 By: Tadessse Kebede(MSc) 114


2.3.3. Methods
▪ As mentioned at the beginning of this chapter, classes usually
consist of two things: instance variables and methods.
▪ Methods are functions that operate on instances of classes in
which they are defined.
▪ Objects can communicate with each other using methods and
can call methods in other classes.
▪ Just as there are class and instance variables, there are class
and instance methods .
▪ Instance methods apply and operate on an instance of the class
while class methods operate on the class .

8/15/2023 By: Tadessse Kebede(MSc) 115


Defining Methods
▪ Method definition has four parts: They are, name of the
method, type of object or primitive type the method returns, a
list of parameters and body of the method.
▪ Java permits different methods to have the same name as long
as the argument list is different. This is called method
overloading. A basic method definition resembles the one given
below :
modifier returntype methodname ( type1 arg1, type2 arg2 ) {
// Body of the methods
}
▪ Here, type specifies the type of data returned by the method.
▪ This can be any valid type, including class types that you
create.

8/15/2023 By: Tadessse Kebede(MSc) 116


Defining Methods…
▪ If the method does not return a value, its return type must be
void.
▪ The name of the method is specified by methodname.
▪ Parameter-list is a sequence of type and identifier pairs
separated by commas.
▪ Parameters are essentially variables that receive the value of
the arguments passed to the method when it is called.
▪ If the method has no parameters, then the parameter list will
be empty.

8/15/2023 By: Tadessse Kebede(MSc) 117


Defining Methods 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 method header specifies the modifiers, return value type, method name, and parameters of
the method.

8/15/2023 By: Tadessse Kebede(MSc) 118


Defining Methods Example…
▪ A method may return a value. The returnValueType is the
data type of the value the method returns.
▪ Some methods perform desired operations without returning a
value. In this case, the returnValueType is the keyword void.
For example, the returnValueType is void in the main method,
as well as in System.exit, System.out.println, and
JOptionPane.showMessageDialog.
▪ If a method returns a value, it is called a valuereturning
method, otherwise it is a void method.
▪ The variables defined in the method header are known as
formal parameters or simply parameters.
▪ A parameter is like a placeholder. When a method is invoked,
you pass a value to the parameter.
▪ This value is referred to as an actual parameter or argument.
8/15/2023 By: Tadessse Kebede(MSc) 119
Defining Methods Example
▪ The parameter list refers to the type, order, and number of the
parameters of a method.
▪ The method name and the parameter list together constitute the
method signature.
▪ Parameters are optional; that is, a method may contain no
parameters. For example, the Math.random() method has no
parameters.
▪ The method body contains a collection of statements that define
what the method does.
▪ The method body of the max method uses an if statement to
determine which number is larger and return the value of that
number. In order for a value-returning method to return a result, a
return statement using the keyword return is required.
▪ The method terminates when a return statement is executed.

8/15/2023 By: Tadessse Kebede(MSc) 120


Method Usage
▪ Methods can be used to reduce redundant code and enable code
reuse.
▪ Methods can also be used to modularize code and improve the
quality of the program.
1 public static int sum(int i1, int i2) {
2 int sum = 0;
3 for (int i = i1; i <= i2; i++)
4 sum += i;
5
6 return sum;
7}
8
9 public static void main(String[] args) {
10 System.out.println("Sum from 1 to 10 is " + sum(1, 10));
11 System.out.println("Sum from 20 to 30 is " + sum(20, 30));
12 System.out.println("Sum from 35 to 45 is " + sum(35, 45));
13 }
8/15/2023 By: Tadessse Kebede(MSc) 121
Adding a Method to a Class
▪ Let’s begin by adding a method to the Box class.
▪ It may have occurred to you while looking at the preceding
programs that the computation of a box’s volume was
something that was best handled by the Box .
▪ After all, since the volume of a box is dependent upon the size
of the box, it makes sense to have the Box class compute it.
▪ To do this, you must add a method to Box.

8/15/2023 By: Tadessse Kebede(MSc) 122


Adding a Method to a Class Example
class Box{ public static void main (String args[]) {
double width; Box bx1 = new Box();
double height; Box bx2 = new Box();
double depth; bx1.width=10;
void volume() { bx1.height=20;
System.out.print("Volume is "); bx1.depth=15;
System.out.println(width*height*depth); bx2.width=3;
} bx2.height=6;
bx2.depth=9;
bx1.volume();
bx2.volume();
}
}
output
Volume is 3000.0
8/15/2023 By: Tadessse Kebede(MSc) 123
Volume is 162.0
Set an instance variables values by method
▪ In the preceding examples, the dimensions of each box had to
be set separately by use of a sequence of statements, such as:
bx.width = 10;
bx.height = 20;
bx.depth = 15;
▪ While this code works, it is troubling for two reasons.
▪ First, it is clumsy and error prone. For example, it would be
easy to forget to set a dimension.
▪ Second, in well-designed Java programs, instance variables
should be accessed only through methods defined by their
class.
▪ Thus, a better approach to setting the dimensions of a box is to
create a method that takes the dimension of a box in its
parameters and sets each instance variable appropriately
8/15/2023 By: Tadessse Kebede(MSc) 124
Set an instance variables values by method Example

▪ As you can see, the setDim( )


method is used to set the
dimensions of each box.
▪ For example, when bx.setDim(10,
20, 15); is executed, 10 is copied
into parameter w, 20 is copied
into h, and 15 is copied into d.
▪ Inside setDim( ) the values of w,
h, and d are then assigned to
width, height, and depth,
respectively

8/15/2023 By: Tadessse Kebede(MSc) 125


Calling a Method
▪ In creating a method, you define what the method is to do. To
use a method, you have to call or invoke it. There are two ways
to call a method, depending on whether the method returns a
value or not.
▪ If the method returns a value, a call to the method is usually
treated as a value. For example, int larger = max(3, 4); calls
max(3, 4) and assigns the result of the method to the variable
larger.
▪ Another example of a call that is treated as a value is
System.out.println(max(3, 4)); which prints the return value of
the method call max(3, 4).
▪ 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
8/15/2023 Java!"); By: Tadessse Kebede(MSc) 126
Calling a Method Example

▪ 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. For example, the code
below shows a complete program
that is used to test the max
method.

8/15/2023 By: Tadessse Kebede(MSc) 127


Calling a Method Example….
▪ When the max method is invoked, the flow of control transfers
to it. Once the max method is finished, it returns control back to
the caller.

8/15/2023 By: Tadessse Kebede(MSc) 128


Returning a Value
// Now, volume () returns the volume of a box.
class Box {
▪ In Java, the return keyword returns a double width ;
value from a method. The method will double height;
double depth ;
return the value immediately when the // compute and return volume
keyword is encountered. double volume () {
▪ This means that the method will not return width * height * depth ;
execute any more statements beyond the }
}
return keyword, and any local variables class BoxDemo {
created in the method will be discarded. public static void main ( String args [ ] ) {
▪ As you can see, when volume( ) is called, Box mybox = new Box ( ) ;
it is put on the right side of an double vol;
// Assign values to mybox’s instance variables
assignment statement. On the left is a mybox.width = 10;
variable, in this case vol, that will mybox.height = 20;
receive the value returned by volume( ) . mybox.depth = 15;
// get volume of box
vol = mybox.volume ( ) ;

System.out..println ( “ Volume is “ + vol );


8/15/2023 By: Tadessse Kebede(MSc) } 129
void Method Example 1

▪ The printGrade method is a void


method. It does not return any
value. A call to a void method
must be a statement. So, it is
invoked as a statement in line 4 in
the main method.
▪ Like any Java statement, it is
terminated with a semicolon.

8/15/2023 By: Tadessse Kebede(MSc) 130


void Method Example 2

▪ To see the differences between a void


and a value-returning method, let us
redesign the printGrade method to
return a value.
▪ The getGrade method defined in lines 7–
18 returns a character grade based on
the numeric score value. The caller
invokes this method in lines 3–4.
▪ The getGrade method can be invoked by
a caller wherever a character may
appear.
▪ The printGrade method does not return
any value. It must be also invoked as a
statement.

8/15/2023 By: Tadessse Kebede(MSc) 131


2.3.4. Parameter Passing…
▪ The parameter is a variable in the method with its own
memory space. The variable is allocated when the method is
invoked, and it disappears when the method is returned to its
caller.
▪ Parameters allow a method to be generalized. That is, a
parameterized method can operate on a variety of data and/or
be used in a number of slightly different situations.
▪ To illustrate this point, let’s use a very simple example.
▪ Here is a method that returns the square of the number 10:
int square()
{
return 10 * 10;
}
▪ While this method does, indeed, return the value of 10
squared, its use is very limited.
8/15/2023 By: Tadessse Kebede(MSc) 132
2.3.4. Parameter Passing
▪ However, if you modify the method so that it takes a
parameter, as shown next, then you can make square( ) much
more useful.
int square(int i)
{
return i * i;
}
▪ Now, square( ) will return the square of whatever value it is
called with.
▪ That is, square( ) is now a general-purpose method that can
compute the square of any integer value, rather than just 10.

8/15/2023 By: Tadessse Kebede(MSc) 133


2.3.4. Parameter Passing
▪ Here is an example:
int x, y;
x = square(5); // x equals 25
x = square(9); // x equals 81
y = 2;
x = square(y); // x equals 4
▪ In the first call to square( ), the value 5 will be passed into
parameter i.
▪ In the second call, i will receive the value 9.
▪ The third invocation passes the value of y, which is 2 in this
example.
▪ As these examples show, square( ) is able to return the square
of whatever data it is passed

8/15/2023 By: Tadessse Kebede(MSc) 134


2.3.4. Parameter Passing
▪ It is important to keep the two terms parameter and argument
straight.
▪ A parameter is a variable defined by a method that receives a
value when the method is called.
▪ For example, in square ( ), i is a parameter.
▪ An argument is a value that is passed to a method when it is
invoked.
▪ For example: square (100) passes 100 as an argument.
▪ Inside square( ), the parameter i receives that value.

8/15/2023 By: Tadessse Kebede(MSc) 135


2.3.5. Passing arguments
▪ There are two ways that a computer language can pass an
argument to a subroutine.(passing by value and passing by
reference).
▪ Passing by- value -This method copies the value of an
argument into the formal parameter of the subroutine.
▪ Therefore, changes made to the parameter variable values
have no effect on the argument variable values.
▪ Used to pass simple data types.(primitive data type)
▪ Passing by reference -In this method, a reference to an
argument (not the value of the argument) is passed to the
parameter.
▪ Changes made to the parameter variable values will affect the
argument variable values.
▪ Used to pass objects.
8/15/2023 By: Tadessse Kebede(MSc) 136
Passing arguments by Values
▪ 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.

8/15/2023 By: Tadessse Kebede(MSc) 137


Passing by Values…
▪ Here, the value of x (1) is passed to the parameter n to invoke the
increment method (line 5). n is incremented by 1 in the method (line 10),
but x is not changed no matter what the method does.
1 public class Increment {
2 public static void main(String[] args) {
3 int x = 1;
4 System.out.println("Before the call, x is " + x);
5 increment(x); //invoke increment
6 System.out.println("after the call, x is " + x);
7}
8
9 public static void increment(int n) {
10 n++;
11 System.out.println("n inside the method is " + n);
12 }
13 }

8/15/2023 By: Tadessse Kebede(MSc) 138


Passing arguments by reference Example
▪ Java is Pass by Value, Not Pass by Reference
public class ByRference {
int a,b;
ByRference(int j,int i) {
a=j;
b=i;
}
void Test(ByRference ref) {
ref.a=ref.a*2;
ref.b=ref.b/2;
}
public static void main(String[] args) {
ByRference reff=new ByRference(15,20);
System.out.println(reff.a+" "+reff.b);
reff.Test(reff);
System.out.println(reff.a+" "+reff.b);
}
}
output:
8/15/2023 15, 20 By: Tadessse Kebede(MSc) 139
30,10
2.3.6. Comparing and Identifying Objects
▪ Comparing objects is a little different than comparing
primitive typed values like numbers.
▪ Objects can be very complex and have many attribute values or
instance variables inside them.
▪ Java provides the two methods of the Object class to compare
the objects are as follows:
o Java equals() Method
o Java hashCode() Method

8/15/2023 By: Tadessse Kebede(MSc) 140


Java equals() Method
▪ In Java, the == operator compares that two references are
identical or not. Whereas the equals() method compares two
objects.
▪ The == comparison operator is designed to compare the value
of two variables. Since the value that is stored for a reference
variable is the memory location, using == will return whether
or not the two objects have the same reference. When two
objects have the same reference, they are said to be aliases.
▪ Objects are equal when they have the same state (usually
comparing variables). Objects are identical when they share
the class identity.
▪ For example, the expression obj1==obj2 tests the identity, not
equality. While the expression obj1.equals(obj2) compares
equality.
8/15/2023 By: Tadessse Kebede(MSc) 141
Java equals() Method
▪ In Java, the method that is used is called .equals(). This
method is called from a variable and it passes a parameter to
compare to in order to determine if the values are equal.
▪ If you assume that one rectangle equals another rectangle if
they have the same width and height, then .equals() can return
true if the method compares the width and height of two
rectangles and finds them to be the same.
▪ Take a look at the example below:
Rectangle one = new Rectangle(3,7);
Rectangle two = new Rectangle(3,7);
boolean isAlias = one == two; // Will be set to false
boolean isEqual = one.equals(two); // Will be set to true

8/15/2023 By: Tadessse Kebede(MSc) 142


Java hashCode() Method
▪ In Java, hash code is a 32-bit signed integer value.
▪ It is a unique id provided by JVM to Java object.
▪ Each Java object is associated with the hash code.
▪ The hash code is managed by a hash-based data structure,
such as HashTable, HashSet, etc.
▪ Syntax: public int hashCode()
▪ It returns a randomly generated hash code value of the object
that is unique for each instance. The randomly generated
value might change during the several executions of the
program.
▪ When it is invoked more than once during the execution of an
application, the hashCode() method will consistently return
the same hash code (integer value). Note that the object should
not be modified.
8/15/2023 By: Tadessse Kebede(MSc) 143
Java hashCode() Method Example
1.public class Employee 1.public class HashcodeExample
2.{ 2.{
3.private int regno; 3.public static void main(String[] args)
4.private String name; 4.{
5.//constructor of Employee class 5.//creating two instances of the Employee class
6.public Employee(int regno, String name) 6.Employee emp1 = new Employee(918, "Maria");
7.{ 7.Employee emp2 = new Employee(918, "Maria");
8.this.name = name; 8.//invoking hashCode() method
9.this.regno = regno; 9.int a=emp1.hashCode();
10.} 10.int b=emp2.hashCode();
11.public int getRegno() 11.System.out.println("hashcode of emp1 = " + a);
12.{ 12.System.out.println("hashcode of emp2 = " + b);
13.return regno; 13.System.out.println("Comparing objects emp1 and emp2 = " + emp1.equals(emp2));
14.}
15.public void setRegno(int Regno) 14.}
16.{ 15.}
17.this.regno = regno;
18.} Output:
19.public String getName() hashcode of emp1 = 2032578917
20.{ hashcode of emp2 = 1531485190
21.return name; Comparing objects emp1 and emp2 = true
22.}
23.public void setName(String name)
24.{
25.this.name = name;
8/15/2023 26.}
By: Tadessse Kebede(MSc) 144
2.3.7. Destroying Objects or Garbage Collection
▪ In Java, objects are automatically destroyed through a process called
garbage collection.
▪ Garbage collection is responsible for reclaiming memory occupied by objects
that are no longer accessible.
▪ When there are no references to an object, it becomes eligible for garbage
collection.
▪ Java's garbage collection eliminates many common programming errors
like dangling pointers and memory leaks.
▪ Garbage collection is handled by the system, relieving programmers from
managing memory explicitly.
▪ Garbage collector calls finalize() method for clean up activity before
destroying the object.
▪ The garbage collector in Java can be called explicitly using the following
method: System.gc();
▪ System.gc() is a method in Java that invokes garbage collector which will
destroy the unreferenced objects. System.gc() calls finalize() method only
once for each object.
8/15/2023 By: Tadessse Kebede(MSc) 145
2.3.7. Destroying Objects or Garbage Collection…
▪ Consider the following two statements (though in reality, you’d
never do anything like this):
Student std = new Student(" John Smith ");
std = null;
▪ In the first line, a reference to a newly created Student object is stored in
the variable std.
▪ But in the next line, the value of std is changed, and the reference to the
Student object is gone.
▪ In fact, there are now no references whatsoever to that object stored in any
variable.
▪ So there is no way for the program ever to use the object again. It might as
well not exist.
▪ In fact, the memory occupied by the object should be reclaimed to be used
for another purpose.
▪ Hence, it is eligible for garbage collection. The garbage collector
calls finalize() method to perform clean-up before destroying the object
8/15/2023 By: Tadessse Kebede(MSc) 146
2.3.8. Enumerated Types
▪ An enum is a special "class" that represents a group of
constants (unchangeable variables, like final variables).
▪ To create an enum, use the enum keyword (instead of class or
interface), and separate the constants with a comma.
▪ You can access enum constants with the dot syntax:
▪ Note that they should be in uppercase letters:
enum Level {
LOW,
MEDIUM,
HIGH
}
public class Main {
public static void main(String[] args) {
Level myVar = Level.MEDIUM;
System.out.println(myVar);
}
}
8/15/2023 By: Tadessse Kebede(MSc) 147
2.4. Instance fields
▪ Java lets you declare two types of fields for a class:
• Class fields
• Instance fields
▪ Class fields are class variables and Instance fields are instance variables.
▪ A class variable is also known as a static variable. an instance variable is
also known as a non-static variable.
▪ All class variables must be declared using the static keyword as a modifier.
▪ Difference: Class field only have one instance while the instance field can
have as many instances as you create.
▪ Declaration of a Employee Class with One Class Variable and Two Instance
Variables
class Employee {
String name; // An instance variable
String gender; // An instance variable
static long count; // A class variable because of the static modifier
}

8/15/2023 By: Tadessse Kebede(MSc) 148


Instance fields Example
public class VariableExample{
int myVariable;
static int data = 30;

public static void main(String args[]){


int a = 100;
VariableExample obj = new VariableExample();

System.out.println("Value of instance variable myVariable: "+obj.myVariable);


System.out.println("Value of static variable data: "+VariableExample.data);
System.out.println("Value of local variable a: "+a);
}
}
Output
Value of instance variable myVariable: 0
Value of static variable data: 30
Value of local variable a: 100

8/15/2023 By: Tadessse Kebede(MSc) 149


2.5. Constructors
▪ It can be tedious to initialize all of the variables in a class each
time an instance is created.
▪ It is possible to initialize objects they are created by:
• Using the dot operator
• The help of methods
▪ But it would be simpler and more concise to initialize an object
when it is first created.
▪ Java supports a special type of method, called a constructor,
that enables an object to initialize itself when it is created.
▪ Constructors are special methods that are used to construct an
instance of a class.
▪ A constructor initializes an object immediately upon creation.
▪ Call the constructor(s) preceding it with the new keyword.

8/15/2023 By: Tadessse Kebede(MSc) 150


Rules with constructors
▪ The definition of a constructor looks much like the definition of
any other method, with three differences.
1. A constructor does not have any return type (not even void).
2. The name of the constructor must be the same as the name of the class
in which it is defined.
3. The only modifiers that can be used on a constructor definition are the
access modifiers public, private, and protected. (In particular, a
constructor can’t be declared static, abstract , final , native , static , or
synchronized.)
Constructor Normal method
Has no return type Has return type
Its name should the Its name can be any
same as class name identifier
Invoked with new Can be invoked without
keyword. new keyword.

8/15/2023 By: Tadessse Kebede(MSc) 151


Types of constructor
1. Default constructor: is a constructor which receives no
arguments.
• has no parameters
• Default parameters defined automatically (if there is no
parameterized constructor)
• Default parameters defined by the programmer.
2. Parameterized Constructor:- is a constructor which can receives
one or more arguments.
• has one or more parameters
• When an instance of an object is created then the instance
will call the constructor.
• It will be called based on the types of constructor that has
been called while object is created.

8/15/2023 By: Tadessse Kebede(MSc) 152


Default of constructor Example
Class employee{
employee() //default constructor
{
System.out.println(“Hello”);
}
public static void main(String args[]) {
Employee emp = new employee();
}
}
Output
Hello

8/15/2023 By: Tadessse Kebede(MSc) 153


Parameterized constructor Example
class employee{
String Ename;
float salary;
employee(String name, float sal) //parameterized constructor
{
Ename= name;
salary = sal;
System.out.println(Ename +”\t”+ salary);
}
public static void main(String args[]) {
Employee emp = new employee(“Teborne”,4500.00);
}
}
Output
=====
Teborne 4500.00
8/15/2023 By: Tadessse Kebede(MSc) 154
Overloaded constructor
▪ Constructor with the same name, but the compiler uses two mechanism to
differentiate the overloaded constructors.
• number of parameter
• data type of parameter
public class students{
String name;
students() {
System.out.println(“default constructor”);
}
students(String name) {
this.name=name;
System.out.println(this.name);
}
public static void main(String[] args){
students stud1=new students();
students stud2=new students(“Teborne”);
}
}
Output
default constructor
Teborne
8/15/2023 By: Tadessse Kebede(MSc) 155
“This” keyword
▪ this -> implicit reference to current object.
▪ Allow us to use the same identifier for instance variable and local variable
▪ To prevent instance variables hiding by local variable
▪ The this keyword refers to the current object in a method or constructor.
▪ used to:
✓ prevent instance variables hiding by local variable.
✓ improve readability of the program
✓ invoke the constructor.

class students{
String name;
students(String name)
{
this.name=name;
}
}

8/15/2023 By: Tadessse Kebede(MSc) 156


Using objects as parameter
public class Boxx {
double wid,het,dep;
Boxx() {
}
Boxx(Boxx bx) { //Using object as parameter
wid=bx.wid;
het=bx.het;
dep=bx.dep;
System.out.println(wid*het*dep);
}
public static void main(String[] args){
Boxx b=new Boxx();
b.wid=10;
b.het=20;
b.dep=15;
Boxx bb=new Boxx(b);
}
}
Output
3000

8/15/2023 By: Tadessse Kebede(MSc) 157


Returning objects
public class Rectangle {
int len,wid;
Rectangle(int l, int w)
{
len=l;
wid=w;
}
Rectangle getRectangle()
{
Rectangle rect=new Rectangle(10,20);
return rect; //returning object
}
public static void main(String[] args) {
Rectangle r=new Rectangle(40, 50);
Rectangle r2;
r2=r.getRectangle();
System.out.println(r.len+" "+r.wid);
System.out.println(r2.len+" "+r2.wid);
}
}
Output
40 50
8/15/2023 10 20 By: Tadessse Kebede(MSc) 158
2.6. Access Modifiers
▪ The access modifiers in Java specifies the accessibility or scope
of a field, method, constructor, or class.
▪ We can change the access level of fields, constructors, methods,
and class by applying the access modifier on it.
▪ There are four types of Java access modifiers:
• Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
• Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.
• Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
• Public: The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside the
package.
8/15/2023 By: Tadessse Kebede(MSc) 159
Private access modifier
▪ In this example, we have created two classes A and Simple. A class
contains private data member and private method. We are accessing
these private members from outside the class, so there is a compile-time
error.
1.class A{
2.private int data=40;
3.private void msg(){
4.System.out.println("Hello java");
5.}
6.}
7.
8.public class Simple{
9. public static void main(String args[]){
10. A obj=new A();
11. System.out.println(obj.data);//Compile Time Error
12. obj.msg();//Compile Time Error
8/15/2023
13. } By: Tadessse Kebede(MSc) 160
14.}
Role of Private Constructor
▪ If you make any class constructor private, you cannot create the instance
of that class from outside the class. For example:
1.class A{
2.private A(){}//private constructor
3.void msg(){System.out.println("Hello java");}
4.}
5.public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9.}

8/15/2023 By: Tadessse Kebede(MSc) 161


Default Modifiers
▪ If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within
package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is
more restrictive than protected, and public.
▪ Example of default access modifier
▪ In this example, we have created two packages pack and mypack. We are accessing the A class from outside
its package, since A class is not public, so it cannot be accessed from outside the package.
1.//save by A.java
2.package pack;
3.class A{
4. void msg(){System.out.println("Hello");}
5.}
6.//save by B.java
7.package mypack;
8.import pack.*;
9.class B{
10. public static void main(String args[]){
11. A obj = new A();//Compile Time Error
12. obj.msg();//Compile Time Error
13. }
14.}
▪ In the above example, the scope of class A and its method msg() is default so it cannot be accessed from
outside the package.

8/15/2023 By: Tadessse Kebede(MSc) 162


Protected access modifier
▪ The protected access modifier is accessible within package and outside the package but
through inheritance only.
▪ The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
▪ It provides more accessibility than the default modifier.
▪ Example of protected access modifier
▪ In this example, we have created the two packages pack and mypack. The A class of pack package
is public, so can be accessed from outside the package. But msg method of this package is
declared as protected, so it can be accessed from outside the class only through inheritance.
1.//save by A.java
2.package pack;
3.public class A{
4.protected void msg(){System.out.println("Hello");}
5.}
1.//save by B.java
2.package mypack;
3.import pack.*;
4.
5.class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10.}
Output:
8/15/2023 Hello
By: Tadessse Kebede(MSc) 163
Public access modifier
▪ The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.
Example of public access modifier
1.//save by A.java
2.
3.package pack;
4.public class A{
5.public void msg(){System.out.println("Hello");}
6.}
1.//save by B.java
2.
3.package mypack;
4.import pack.*;
5.
6.class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11.}
Output:Hello

8/15/2023 By: Tadessse Kebede(MSc) 164


2.7. Encapsulation
▪ Encapsulation in Java is a process of wrapping code and data
together into a single unit, for example, a capsule which is mixed of
several medicines.
▪ We can create a fully encapsulated class in Java by making all the
data members of the class private.
▪ Now we can use setter and getter methods to set and get the data in
it.
▪ To prevent direct modifications of data fields, you should declare the
data fields private, using the private modifier.
▪ This is known as data field encapsulation.
▪ A private data field cannot be accessed by an object from outside the
class that defines the private field. But often a client needs to
retrieve and modify a data field. To make a private data field
accessible, provide a get method to return its value.
▪ To enable a private data field to be updated, provide a set method to
set a new value.
8/15/2023 By: Tadessse Kebede(MSc) 165
2.7. Encapsulation…
▪ In encapsulation the variables of a class will be hidden from
other classes, and can be accessed only through the methods of
their current class, therefore it is also known as data hiding.
▪ To achieve encapsulation in Java:
• Declare the variables and methods of a class as private.
• Provide public setter and getter methods to access and
modify the variables values.
▪ setter and getter: setter method used to set/initialize instance
variables, and getter method used to accept the instance
variable value that has been set by the setter method
▪ Example: if the instance variable is name:
✓ setter method = setName(param),
✓ getter method =getName()

8/15/2023 By: Tadessse Kebede(MSc) 166


2.7. Encapsulation…
▪ A get method has the following signature:
public returnType getPropertyName()
▪ If the returnType is boolean, the get method should be defined
as follows by convention:
public boolean isPropertyName()
▪ A set method has the following signature:
public void setPropertyName(dataType propertyValue)

8/15/2023 By: Tadessse Kebede(MSc) 167


Advantage of Encapsulation in Java
▪ By providing only a setter or getter method, you can make the
class read-only or write-only. In other words, you can skip the
getter or setter methods.
▪ It provides you the control over the data. Suppose you want to
set the value of id which should be greater than 100 only, you
can write the logic inside the setter method. You can write the
logic not to store the negative numbers in the setter methods.
▪ It is a way to achieve data hiding in Java because other class
will not be able to access the data through the private data
members.
▪ The encapsulate class is easy to test. So, it is better for unit
testing.

8/15/2023 By: Tadessse Kebede(MSc) 168


Encapsulation Example
1.//A Account class which is a fully encapsulated class. 23. public void setEmail(String email) {
2.//It has a private data member and getter and setter 24. this.email = email;
25. }
methods.
26. public float getAmount() {
3.class Account { 27. return amount;
4.//private data members 28. }
5.private long acc_no; 29. public void setAmount(float amount) {
6.private String name,email; 30. this.amount = amount;
7.private float amount; 31. }
8.//public getter and setter methods 33. }
1.//A Java class to test the encapsulated class Account.
9.public long getAcc_no() {
2.public class TestEncapsulation {
10. return acc_no; 3.public static void main(String[] args) {
11.} 4. //creating instance of Account class
12.public void setAcc_no(long acc_no) { 5. Account acc=new Account();
13. this.acc_no = acc_no; 6. //setting values through setter methods
14.} 7. acc.setAcc_no(1000234567);
15.public String getName() { 8. acc.setName(“John Marsil");
9. acc.setEmail(“marsil@gamil.com");
16. return name;
10. acc.setAmount(2000ETB);
17.} 11. //getting values through getter methods
18.public void setName(String name) { 12. System.out.println(acc.getAcc_no()+" "+acc.getName()+"
19. this.name = name; "+acc.getEmail()+" "+acc.getAmount());
20.} 13.}
21.public String getEmail() { 14.}
8/15/2023 22. return email; By: Tadessse Kebede(MSc) 169
End-of-Chapter-2

8/15/2023 By: Tadessse Kebede(MSc) 170

You might also like