Unit 2 Oopj
Unit 2 Oopj
1
04 -1 2 -2 0 2 4
Class Fundamentals
A class is a blueprint for the object. Before we create an object,
we first need to define the class.
A class is a template that defines the form of an object. It
specifies both the data and the code that will operate on that data.
Objects are instances of a class.
Thus, a class is essentially a set of plans that specify how to build an
object.
Java Class
When you define a class, you declare its exact form and nature.
We can create a class in Java using the class keyword.
For example,
2
04 -1 2 -2 0 2 4
3
04 -1 2 -2 0 2 4
Java Objects
An object is called an instance(member) of a class.
For example, suppose Bicycle is a class then MountainBicycle,
SportsBicycle, TouringBicycle, etc can be considered as objects of
the class.
4
04 -1 2 -2 0 2 4
5
04 -1 2 -2 0 2 4
6
04 -1 2 -2 0 2 4
7
04 -1 2 -2 0 2 4
Java Methods
A method is a block of code that performs a specific task.
Suppose you need to create a program to create a circle and
color it.
You can create two methods to solve this problem:
a method to draw the circle
a method to color the circle
Dividing a complex problem into smaller chunks makes your
program easy to understand and reusable.
Java Methods
In Java, there are two types of methods:
User-defined Methods: We can create our own method based on our
requirements.
Standard Library Methods: These are built-in methods in Java that
are available to use.
8
04 -1 2 -2 0 2 4
In the above example, the name of the method is adddNumbers() and the return
type is int.
This is the simple syntax of declaring a method.
However, the complete syntax of declaring a method is:
9
04 -1 2 -2 0 2 4
10
04 -1 2 -2 0 2 4
Here, we have called the method by passing two arguments num1 and
num2.
Since the method is returning some value, we have stored the value in the result
variable.
11
04 -1 2 -2 0 2 4
Here, we are returning the variable sum. Since the return type of the
function is int.
The sum variable should be of int type.
Otherwise, it will generate an error.
Mrs. Divya Patel 23
12
04 -1 2 -2 0 2 4
13
04 -1 2 -2 0 2 4
14
04 -1 2 -2 0 2 4
15
04 -1 2 -2 0 2 4
16
04 -1 2 -2 0 2 4
Exercise
What are the advantages of using methods?
1. The main advantage is code reusability. We can write a method once, and
use it multiple times. We do not have to rewrite the entire code each
time. Think of it as, "write once, reuse multiple times".
2. Methods make code more readable and easier to debug. Here, the
getSquare() method keeps the code to compute the square in a block. Hence,
makes it more readable.
17
04 -1 2 -2 0 2 4
Constructors
A constructor in Java is similar to a method that is invoked when an object
of the class is created.
Unlike Java methods, a constructor has the same name as that of the class and
does not have any return type.
For example,
Constructors
Here, Test() is a
constructor.
It has the same name as
that of the class and
doesn't have a return type.
18
04 -1 2 -2 0 2 4
Constructors
In the above example, we have created a constructor named Main(). Inside the
constructor, we are initializing the value of the name variable.
Notice the statement of creating an object of the Main class.
Here, when the object is created, the Main() constructor is called. And, the
value of the name variable is initialized.
Hence, the program prints the value of the name variables as FYMCA.
Types of Constructors
In Java, constructors can be divided into 3 types:
1. No-Argumrnt Constructor
2. Parameterized Constructor
3. Default Constructor
19
04 -1 2 -2 0 2 4
20
04 -1 2 -2 0 2 4
21
04 -1 2 -2 0 2 4
22
04 -1 2 -2 0 2 4
Garbage Collection
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory
automatically.
In other words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++.
But, in java it is performed automatically. So, java provides better memory
management.
Garbage Collection
Advantage of Garbage Collection:-
It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
It is automatically done by the garbage collector(a part of JVM), so we
don't need to make extra efforts.
23
04 -1 2 -2 0 2 4
Garbage Collection
Garbage Collection
1. By nulling a reference:
3. By anonymous object:
24
04 -1 2 -2 0 2 4
25
04 -1 2 -2 0 2 4
26
04 -1 2 -2 0 2 4
27
04 -1 2 -2 0 2 4
28
04 -1 2 -2 0 2 4
Here, the Logger class has the default access modifier. And the class is visible to
all the classes that belong to the defaultPackage package.
However, if we try to use the Logger class in another class outside of
defaultPackage, we will get a compilation error.
Mrs. Divya Patel 57
29
04 -1 2 -2 0 2 4
The error is generated because we are trying to access the private variable of the
Data class from the Main class.
30
04 -1 2 -2 0 2 4
31
04 -1 2 -2 0 2 4
32
04 -1 2 -2 0 2 4
33
04 -1 2 -2 0 2 4
Returning Objects
In java, a method can return any type of data, including objects.
For example, in the following program, the incrByTen() method returns an object
in which the value of a(an integer variable) is ten greater than it is in the
invoking object.
34
04 -1 2 -2 0 2 4
Returning Objects
Returning Objects
As you can see, each time the method incrByTen() is invoked, a new object is
created, and a reference to it is returned to the calling routine.
The preceding program makes another important point i.e., since all the objects
are dynamically allocated using the new operator/keyword, you don't need to
worry about an object going out-of-scope because the method in which it was
created terminates.
The object will continue to exist as long as there is a reference to it somewhere in
your program.
When there are no references to it, the object will be reclaimed the next time
garbage collection takes place.
35
04 -1 2 -2 0 2 4
Method Overloading
In Java, two or more methods may have the same name if they differ in
parameters(different number of parameters, different types of parameters, or
both). These methods are called overloaded methods and this feature is
called method overloading.
For example:
Here, the func() method is overloaded. These methods have the same name but
accept different arguments.
36
04 -1 2 -2 0 2 4
37
04 -1 2 -2 0 2 4
Method Overloading
Important Points:-
Two or more methods can have the same name inside the same class if they
accept different arguments. This feature is known as method overloading.
Method overloading is achieved by either:
changing the number of arguments.
or changing the data type of arguments.
It is not method overloading if we only change the return type of methods.
There must be differences in the number of parameters.
38
04 -1 2 -2 0 2 4
Overloading Constructors
Similar to Java method overloading, we can also create two or more
constructors with different parameters. This is called constructors
overloading.
Example of Java Constructor Overloading:
Overloading Constructors
39
04 -1 2 -2 0 2 4
Overloading Constructors
In the above example, we have two constructors: Main() and Main(String
language).
Here, both the constructor initialize the value of the variable language with
different values.
Based on the parameter passed during object creation, different constructors are
called and different values are assigned.
It is also possible to call one constructor from another constructor.
Recursion
In Java, a method that calls itself is known as a recursive method. And, this
process is known as recursion.
A physical world example would be to place two parallel mirrors facing each
other. Any object in between them would be reflected recursively.
In the below example, we have called the recurse() method from inside the main
method. (normal method call).
And, inside the recurse() method, we are again calling the same recurse method.
This is a recursive call.
40
04 -1 2 -2 0 2 4
Recursion
Recursion
41
04 -1 2 -2 0 2 4
Recursion
In the above example, we have a method named factorial(). The factorial() is
called from the main() method. with the number variable passed as an argument.
Here, notice the statement,
The factorial() method is calling itself. Initially, the value of n is 4 inside
factorial(). During the next recursive call, 3 is passed to the factorial() method.
This process continues until n is equal to 0.
When n is equal to 0, the if statement returns false hence 1 is returned. Finally,
the accumulated result is passed to the main() method.
Static Keyword
In Java, if we want to access class members, we must first create an instance
of the class.
But there will be situations where we want to access class members without
creating any instance variables.
In those situations, we can use the static keyword in Java.
If we want to access class members without creating an instance of the class,
we need to declare the class members static.
The Math class in Java has almost all of its members are static. So, we can
access its members without creating instances of the Math class.
For example,
Mrs. Divya Patel 84
42
04 -1 2 -2 0 2 4
Static Keyword
Static Keyword
In the above example, we have not created any instances of the Math class.
But we are able to access its methods: abs() and pow() and variables: PI and
E.
It is possible because the methods and variables of the Math class are static.
43
04 -1 2 -2 0 2 4
Static Methods
Static methods are also called class methods. It is because a static method
belongs to the class rather than the object of a class.
And we can invoke static methods directly using the class name.
For example,
Static Methods
Here, we can see that the static method can be accessed directly from other
classes using the class name.
In every Java program, we have declared the main method static.
It is because to run the program the JVM should be able to invoke the main
method during the initial phase where no objects exist in the memory.
44
04 -1 2 -2 0 2 4
Static Methods
Static Methods
In the above program, we have declared a non-static method named multiply()
and a static method named add() inside the class StaticTest.
Inside the Main class, we can see that we are calling the non-static method using
the object of the class (st.multiply(2, 2)).
However, we are calling the static method by using the class name
(StaticTest.add(2, 3)).
45
04 -1 2 -2 0 2 4
Static Variables
In Java, when we create objects of a class, then every object will have its own
copy of all the variables of the class.
For example,
Here, both the objects test1 and test2 will have separate copies of the variable
age. And, they are different from each other.
Static Variables
However, if we declare a variable static, all objects of the class share the
same static variable.
It is because like static methods, static variables are also associated with the
class.
And, we don't need to create objects of the class to access the static variables.
For example,
Here, we can see that we are accessing the static variable from the other class
using the class name.
Mrs. Divya Patel 92
46
04 -1 2 -2 0 2 4
Static Variables
Static Variables
In the above program, we have declared a non-static variable named min and a
static variable named max inside the class Test.
Inside the Main class, we can see that we are calling the non-static variable using
the object of the class (obj.min + 1).
However, we are calling the static variable by using the class name (Test.max +
1).
47
04 -1 2 -2 0 2 4
Static Blocks
In Java, static blocks are used to initialize the static variables.
For example,
Here, we can see that we have used a static block with the syntax:
Static Blocks
The static block is executed only once when the class is loaded in memory.
The class is loaded if either the object of the class is requested in code or the
static members are requested in code.
A class can have multiple static blocks and each static block is executed in the
same sequence in which they have been written in a program.
48
04 -1 2 -2 0 2 4
Static Blocks
Static Blocks
In the above program, as soon as the Main class is loaded,
The value of a is set to 23.
The first static block is executed. Hence, the string First Static block is printed
and the value of b is set to a * 4.
The second static block is executed. Hence, the string Second Static block is
printed and the value of max is set to 30.
And finally, the print statements inside the method display() are executed.
49
04 -1 2 -2 0 2 4
There are two types of nested classes you can create in Java.
Non-static nested class (inner class)
Static nested class
50
04 -1 2 -2 0 2 4
51
04 -1 2 -2 0 2 4
We use the dot (.) operator to create an instance of the inner class using the
outer class.
Mrs. Divya Patel 103
Here, we are creating an object of the static nested class by simply using the
class name of the outer class. Hence, the outer class cannot be referenced using
OuterClass.this.
52
04 -1 2 -2 0 2 4
Here, we are creating an object of USB using the name of the outer class.
53
04 -1 2 -2 0 2 4
54
04 -1 2 -2 0 2 4
55
04 -1 2 -2 0 2 4
56
04 -1 2 -2 0 2 4
57
04 -1 2 -2 0 2 4
58
04 -1 2 -2 0 2 4
In this case, compiler cannot figure out the number of arguments passed to nums.
59
04 -1 2 -2 0 2 4
60