0% found this document useful (0 votes)
9 views60 pages

Unit 2 Oopj

The document provides an overview of class fundamentals in Java, explaining the concepts of classes, objects, methods, and constructors. It details how to create classes and objects, access class members, and the significance of methods and constructors in object-oriented programming. Additionally, it covers topics like garbage collection, method parameters, and the use of the 'this' keyword.

Uploaded by

Divya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views60 pages

Unit 2 Oopj

The document provides an overview of class fundamentals in Java, explaining the concepts of classes, objects, methods, and constructors. It details how to create classes and objects, access class members, and the significance of methods and constructors in object-oriented programming. Additionally, it covers topics like garbage collection, method parameters, and the use of the 'this' keyword.

Uploaded by

Divya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

04 -1 2 -2 0 2 4

Object Oriented Programming in JAVA

Unit2 - Class Fundamentals

Mrs. Divya Patel 1

Chapter 4 - Introducing Classes, Objects,


and Methods

Mrs. Divya Patel 2

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.

Mrs. Divya Patel 3

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,

 Here, fields (variables) and methods behaviour of the object


represent the state and respectively.
 fields are used to store data
 methods are used to perform some operations

Mrs. Divya Patel 4

2
04 -1 2 -2 0 2 4

Create a class in Java


 For our bicycle object, we
can create the class as:
 In this example, we have
created a class named
Bicycle. It contains a field
named gear and a method
named braking().

Mrs. Divya Patel 5

Create a class in Java


 Here, Bicycle is a prototype. Now, we can create any number of
bicycles using the prototype. And, all the bicycles will share the
fields and methods of the prototype.
 We have used keywords private and public.
 These are known as access modifiers.

Mrs. Divya Patel 6

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.

Mrs. Divya Patel 7

Creating an Object in Java


 Here is how we can create an object of
a class.
 We have used the new keyword along
with the constructor of the class to
create an object.
 Constructors are similar to methods and
have the same name as the class.
 For example, Bicycle() is the
constructor of the Bicycle class.

Mrs. Divya Patel 8

4
04 -1 2 -2 0 2 4

Creating an Object in Java


 Here, sportsBicycle and touringBicycle are the names of objects. We
can use them to access fields and methods of the class.
 As you can see, we have created two objects of the class. We can
create multiple objects of a single class in Java.

Mrs. Divya Patel 9

Access Members of a Class


 We can use the name of objects
along with the . operator to access
members of a class.
 In this example, we have created a
class named Bicycle. It includes a field
named gear and a method named
braking().
 Notice the statement,

Mrs. Divya Patel 10

5
04 -1 2 -2 0 2 4

Access Members of a Class

 Here, we have created an object of Bicycle named sportsBicycle.


 We then use the object to access the field and method of the class.
 sportsBicycle.gear - access the field gear
 sportsBicycle.braking() - access the method braking()

Mrs. Divya Patel 11

Java Class and Objects

Mrs. Divya Patel 12

6
04 -1 2 -2 0 2 4

Java Class and Objects


 In the above program, we have created a class named Lamp.
 It contains a variable: isOn and two methods: turnOn() and
turnOff().
 Inside the Main class, we have created two objects: led and halogen
of the Lamp class.
 We then used the objects to call the methods of the class.
 led.turnOn() - It sets the isOn variable to true and prints the output.
 halogen.turnOff() - It sets the isOn variable to false and prints the output.

Mrs. Divya Patel 13

Java Class and Objects


 The variable isOn defined inside the class is also called an instance
variable.
 It is because when we create an object of the class, it is called an
instance of the class.
 And, each instance will have its own copy of the variable.
 That is, led and halogen objects will have their own copy of the isOn
variable.

Mrs. Divya Patel 14

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.

Mrs. Divya Patel 15

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.

Mrs. Divya Patel 16

8
04 -1 2 -2 0 2 4

Declaring a Java User-defined Method


 The syntax to declare a method is:

 Here, returnType - It specifies what type of value a method returns. For


example, if a method has an int return type then it returns an integer value. If
the method does not return a value, its return type is void.
 methodName – It is an identifier that is used to refer to the particular method in
a program.
 method body - It includes the programming statements that are used to
perform some tasks. The method body is enclosed inside the curly braces { }.

Mrs. Divya Patel 17

Declaring a Java Method

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

Mrs. Divya Patel 18

9
04 -1 2 -2 0 2 4

Declaring a Java Method


 Here, modifier - It defines access types whether the method is public, private,
and so on.
 static – If we use the static keyword, it can be accessed without creating
objects.
 For example, the sqrt() method of standard Math class is static. Hence,
we can directly call Math.sqrt() without creating an instance of Math class.
 parameter1/parameter2 - These are values passed to a method. We can pass
any number of arguments to a method.

Mrs. Divya Patel 19

Calling a Method in Java


 In the above example, we have declared a method named addNumbers().

 Now, to use the method, we need to call it.


 Here's is how we can call the addNumbers() method.

Mrs. Divya Patel 20

10
04 -1 2 -2 0 2 4

Calling a Method in Java

Mrs. Divya Patel 21

Calling a Method in Java


 In the above example, we have created a method named addNumbers(). The
method takes two parameters a and b.
 Notice the line,

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

Mrs. Divya Patel 22

11
04 -1 2 -2 0 2 4

Java Method Return Type


 A Java method may or may not return a value to the function
call.
 We use the return statement to return any value. For example,

 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

Java Method Return Type

Mrs. Divya Patel 24

12
04 -1 2 -2 0 2 4

Java Method Return Type


 In the above program, we have created a method named square().
 The method takes a number as its parameter and returns the square of the
number.
 Here, we have mentioned the return type of the method as int.
 Hence, the method should always return an integer value.

Mrs. Divya Patel 25

Java Method Return Type


 If the method does not return any value, we use the void keyword as the
return type of the method.
 For example,

Mrs. Divya Patel 26

13
04 -1 2 -2 0 2 4

Method Parameters in Java


 A method parameter is a value accepted by the method. As mentioned
earlier, a method can also have any number of parameters.
 For example,

Mrs. Divya Patel 27

Method Parameters in Java


 If a method is created with parameters, we need to pass the corresponding
values while calling the method.
 For example,

Mrs. Divya Patel 28

14
04 -1 2 -2 0 2 4

Method Parameters in Java

Mrs. Divya Patel 29

Method Parameters in Java


 Here, the parameter of the method is int. Hence, if we pass any other data type
instead of int, the compiler will throw an error. It is because Java is a strongly
typed language.
 The argument 24 passed to the display2() method during the method call is
called the actual argument.
 The parameter a accepted by the method definition is known as a formal
argument.
 We need to specify the type of formal arguments. And, the type of actual
arguments and formal arguments should always match.

Mrs. Divya Patel 30

15
04 -1 2 -2 0 2 4

Standard Library Methods


 The standard library methods are built-in methods in Java that are readily
available for use.
 These standard libraries come along with the Java Class Library (JCL) in a
Java archive (*.jar) file with JVM and JRE.
 For example,
 print() is a method of java.io.PrintSteam. The print("...") method prints the
string inside quotation marks.
 sqrt() is a method of Math class. It returns the square root of a number.

Mrs. Divya Patel 31

Standard Library Methods

Mrs. Divya Patel 32

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.

Mrs. Divya Patel 33

Mrs. Divya Patel 34

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,

Mrs. Divya Patel 35

Constructors
 Here, Test() is a
constructor.
 It has the same name as
that of the class and
doesn't have a return type.

Mrs. Divya Patel 36

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.

Mrs. Divya Patel 37

Types of Constructors
 In Java, constructors can be divided into 3 types:
1. No-Argumrnt Constructor
2. Parameterized Constructor
3. Default Constructor

Mrs. Divya Patel 38

19
04 -1 2 -2 0 2 4

Java Parameterized Constructor


 A Java constructor can also accept one or more parameters.
 Such constructors are known as parameterized constructors (constructor
with parameters).

Mrs. Divya Patel 39

Java Parameterized Constructor

Mrs. Divya Patel 40

20
04 -1 2 -2 0 2 4

Java Parameterized Constructor


 In the above example, we have created a constructor named Main(). Here, the
constructor takes a single parameter.
 Notice the expression,

 Here, we are passing the single value to the constructor.


 Based on the argument passed, the language variable is initialized inside the
constructor.

Mrs. Divya Patel 41

Difference between constructor and method


in Java

Mrs. Divya Patel 42

21
04 -1 2 -2 0 2 4

The new Operator


 The new operator is used in Java to create new objects.
 It can also be used to create an array object.
 Let us first see the steps when creating an object from a class −
 Declaration − A variable declaration with a variable name with an object
type.
 Instantiation − The 'new' keyword is used to create the object.
 Initialization − The 'new' keyword is followed by a call to a constructor. This
call initializes the new object.

Mrs. Divya Patel 43

The new Operator

Mrs. Divya Patel 44

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.

Mrs. Divya Patel 45

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.

Mrs. Divya Patel 46

23
04 -1 2 -2 0 2 4

Garbage Collection

Mrs. Divya Patel 47

Garbage Collection
1. By nulling a reference:

2. By assigning a reference to another:

3. By anonymous object:

Mrs. Divya Patel 48

24
04 -1 2 -2 0 2 4

The this Keyword


 In Java, this keyword is used to refer to the current object inside a
method or a constructor.
 For example,

Mrs. Divya Patel 49

The this Keyword


 In the above example, we created an object named obj of the class Main. We
then print the reference to the object obj and this keyword of the class.
 Here, we can see that the reference of both obj and this is the same. It means
this is nothing but the reference to the current object.

Mrs. Divya Patel 50

25
04 -1 2 -2 0 2 4

The this Keyword

Mrs. Divya Patel 51

Chapter 5 - A Closer Look at Methods and


Classes

Mrs. Divya Patel


52

26
04 -1 2 -2 0 2 4

Java’s Access Modifiers


 Member access control is achieved through the use of three access
modifiers: public, private, and protected.
 If no access modifier is used, the default access setting is assumed.
 In this chapter, we will be concerned with public and private.
 The protected modifier applies only when inheritance is involved.

Mrs. Divya Patel 53

Java’s Access Modifiers


 What are Access Modifiers?
 In Java, access modifiers are used to set the accessibility (visibility) of classes,
interfaces, variables, methods, constructors, data members, and the setter
methods.
 For example,

Mrs. Divya Patel 54

27
04 -1 2 -2 0 2 4

Java’s Access Modifiers


 In the above example, we have declared 2 methods: method1() and
method2(). Here,
 method1 is public - This means it can be accessed by other classes.
 method2 is private - This means it can not be accessed by other classes.
 Note the keyword public and private. These are access modifiers in Java. They
are also known as visibility modifiers.

Mrs. Divya Patel 55

Java’s Access Modifiers


 There are four access modifiers keywords in Java and they are:

Mrs. Divya Patel 56

28
04 -1 2 -2 0 2 4

Java’s Access Modifiers


 Default Access Modifier: If we do not explicitly specify any access modifier
for classes, methods, variables, etc, then by default the default access modifier
is considered.
 For example,

 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

Java’s Access Modifiers


 Private Access Modifier: When variables and methods are declared private,
they cannot be accessed outside of the class.
 For example,

Mrs. Divya Patel 58

29
04 -1 2 -2 0 2 4

Java’s Access Modifiers


 In the above example, we have declared a private variable named name.
 When we run the program, we will get the following error:

 The error is generated because we are trying to access the private variable of the
Data class from the Main class.

Mrs. Divya Patel 59

Java’s Access Modifiers


 You might be
wondering what if we
need to access those
private variables.
 In this case, we can
use the getters and
setters method.
 For example,

Mrs. Divya Patel 60

30
04 -1 2 -2 0 2 4

Java’s Access Modifiers


 Protected Access Modifier: When methods and data members are declared
protected, we can access them within the same package as well as from
subclasses.
 For example,

Mrs. Divya Patel 61

Java’s Access Modifiers


 In the above example, we have a protected method named display() inside the
Animal class. The Animal class is inherited by the Dog class.
 We then created an object dog of the Dog class. Using the object we tried to
access the protected method of the parent class.
 Since protected methods can be accessed from the child classes, we are able to
access the method of Animal class from the Dog class.
 Note: We cannot declare classes or interfaces protected in Java.

Mrs. Divya Patel 62

31
04 -1 2 -2 0 2 4

Java’s Access Modifiers


 Public Access Modifier: When methods, variables, classes, and so on are
declared public, then we can access them from anywhere.
 The public access modifier has no scope restriction.
 For example,

Mrs. Divya Patel 63

Java’s Access Modifiers

 Here, The public class


Animal is accessed from
the Main class.
 The public variable
legCount is accessed
from the Main class.
 The public method
display() is accessed
from the Main class.
Mrs. Divya Patel 64

32
04 -1 2 -2 0 2 4

Pass Objects to Methods (How Arguments


Are Passed)
 Object as an argument is use to establish communication between two or
more objects of same class as well as different class, i.e, user can easily
process data of two same or different objects within function.
 In Java, When a primitive type is passed to a method ,it is done by use of call-
by-value.
 Objects are implicitly passed by use of call-by-reference.
 This means when we pass primitive data types to method it will pass only
values to function parameters, so any change made in parameter will not
affect the value of actual parameters.

Mrs. Divya Patel 65

Pass Objects to Methods (How Arguments


Are Passed)
 Whereas Objects in java are reference variables, so for objects a value which
is the reference to the object is passed.
 Hence the whole object is not passed but its referenced gets passed.
 All modification to the object in the method would modify the object in the
Heap.

Mrs. Divya Patel 66

33
04 -1 2 -2 0 2 4

Pass Objects to Methods (How Arguments


Are Passed)
class Add { public class Main {
int a; public static void main(String arg[]) {
int b; Add A = new Add(5, 8);
/* Calls the parametrized constructor
Add(int x, int y) // parametrized constructor with set of parameters*/
{ A.sum(A);
a = x; }
b = y; }
}
void sum(Add A1) // object 'A1' passed as
Output
parameter in function 'sum' Sum of a and b :13
{
int sum1 = A1.a + A1.b;
System.out.println("Sum of a and b :" + sum1);
}
}

Mrs. Divya Patel 67

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.

Mrs. Divya Patel 68

34
04 -1 2 -2 0 2 4

Returning Objects

Mrs. Divya Patel 69

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.

Mrs. Divya Patel 70

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.

Mrs. Divya Patel 71

Why method overloading?


 Suppose, you have to perform the addition of given numbers but there
can be any number of arguments (let’s say either 2 or 3 arguments for
simplicity).
 In order to accomplish the task, you can create two methods sum2num(int,
int) and sum3num(int, int, int) for two and three parameters respectively.
 However, other programmers, as well as you in the future may get confused as
the behavior of both methods are the same but they differ by name.

Mrs. Divya Patel 72

36
04 -1 2 -2 0 2 4

Why method overloading?


 The better way to accomplish this task is by overloading methods.
 And, depending upon the argument passed, one of the overloaded methods is
called.
 This helps to increase the readability of the program.

Mrs. Divya Patel 73

How to perform method overloading in Java?


 Here are different ways to perform method overloading:
1. Overloading by changing the number of parameters

Mrs. Divya Patel 74

37
04 -1 2 -2 0 2 4

How to perform method overloading in Java?


2. Method Overloading by changing the data type of parameters

Mrs. Divya Patel 75

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.

Mrs. Divya Patel 76

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:

Mrs. Divya Patel 77

Overloading Constructors

Mrs. Divya Patel 78

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.

Mrs. Divya Patel 79

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.

Mrs. Divya Patel 80

40
04 -1 2 -2 0 2 4

Recursion

Mrs. Divya Patel 81

Recursion

Mrs. Divya Patel 82

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.

Mrs. Divya Patel 83

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

Mrs. Divya Patel 85

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.

Mrs. Divya Patel 86

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,

Mrs. Divya Patel 87

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.

Mrs. Divya Patel 88

44
04 -1 2 -2 0 2 4

Static Methods

Mrs. Divya Patel 89

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

Mrs. Divya Patel 90

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.

Mrs. Divya Patel 91

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

Mrs. Divya Patel 93

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

Mrs. Divya Patel 94

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:

Mrs. Divya Patel 95

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.

Mrs. Divya Patel 96

48
04 -1 2 -2 0 2 4

Static Blocks

Mrs. Divya Patel 97

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.

Mrs. Divya Patel 98

49
04 -1 2 -2 0 2 4

Introducing Nested and Inner Classes


 In Java, you can define a class within another class. Such class is known as
nested class.
 For example,

 There are two types of nested classes you can create in Java.
 Non-static nested class (inner class)
 Static nested class

Mrs. Divya Patel 99

Non-Static Nested Class (Inner Class)


 A non-static nested class is a class within another class.
 It has access to members of the enclosing class (outer class).
 It is commonly known as inner class.

Mrs. Divya Patel 100

50
04 -1 2 -2 0 2 4

Non-Static Nested Class (Inner Class)

Mrs. Divya Patel 101

Non-Static Nested Class (Inner Class)

Mrs. Divya Patel 102

51
04 -1 2 -2 0 2 4

Non-Static Nested Class (Inner Class)


 In the above program, there are two nested classes: Processor and RAM inside
the outer class: CPU. We can declare the inner class as protected. Hence, we
have declared the RAM class as protected.
 Inside the Main class, we first created an instance of an outer class CPU named
cpu.
 Using the instance of the outer class, we then created objects of inner classes:

 We use the dot (.) operator to create an instance of the inner class using the
outer class.
Mrs. Divya Patel 103

Static Nested Class


 In Java, we can also define a static class inside another class. Such class is
known as static nested class. Static nested classes are not called static inner
classes.
 Unlike inner class, a static nested class cannot access the member variables of
the outer class. It is because the static nested class doesn't require you to
create an instance of the outer class.

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

Mrs. Divya Patel 104

52
04 -1 2 -2 0 2 4

Static Nested Class

Mrs. Divya Patel 105

Static Nested Class


 In the above program, we have created a static class named USB inside the class
MotherBoard.
 Notice the line,

 Here, we are creating an object of USB using the name of the outer class.

Mrs. Divya Patel 106

53
04 -1 2 -2 0 2 4

Nested and Inner Classes


 Key Points to Remember:
 Java treats the inner class as a regular member of a class. They are just
like methods and variables declared inside a class.
 Since inner classes are members of the outer class, you can apply any access
modifiers like private, protected to your inner class which is not possible in
normal classes.
 Since the nested class is a member of its enclosing outer class, you can use the
dot (.) notation to access the nested class and its members.
 Using the nested class will make your code more readable and provide better
encapsulation.
 Non-static nested classes (inner classes) have access to other members of the
outer/enclosing class, even if they are declared private.
Mrs. Divya Patel 107

Varargs: Variable-Length Arguments


 Let’s suppose you are creating a Java method. However, you are not sure
how many arguments your method is going to accept. To address this
problem, Java 1.5 introduced varargs.
 Varargs is a short name for variable arguments.
 In Java, an argument of a method can accept arbitrary number of values.
This argument that can accept variable number of values is called varargs.
 The syntax for implementing varargs is as follows:

Mrs. Divya Patel 108

54
04 -1 2 -2 0 2 4

Varargs: Variable-Length Arguments


 In order to define vararg, ... (three dots) is used in the formal parameter of a
method.
 A method that takes variable number of arguments is called a variable-arity
method, or simply a varargs method.
 First, let’s look at the example without using varargs:
 As you can clearly see in below example, you had to overload
sumNumber() method to make it work for 3 arguments.

Mrs. Divya Patel 109

Varargs: Variable-Length Arguments

Mrs. Divya Patel 110

55
04 -1 2 -2 0 2 4

Varargs: Variable-Length Arguments


 What if the user wants to add 5 numbers or 10 or 100?
 This can be handled in a neat way with the use of varargs. Let’s see a code
example:

Mrs. Divya Patel 111

Varargs: Variable-Length Arguments

Mrs. Divya Patel 112

56
04 -1 2 -2 0 2 4

Varargs: Variable-Length Arguments


 Here, the sumNumber() method returns the sum of int parameters passed to it
(doesn't matter the number of arguments passed).
 Let's take another example.
 The format() method defined in Java library accepts varargs. In JDK,
the format() method is defined as follows:

Mrs. Divya Patel 113

Varargs: Variable-Length Arguments

Mrs. Divya Patel 114

57
04 -1 2 -2 0 2 4

Overloading Varargs Methods


 Similar to typical methods, you can overload a vararg methods.
 In this program,
test() method is
overloaded by
changing the
number of
arguments it
accepts.

Mrs. Divya Patel 115

Overloading Varargs Methods


 Things to remember while using Varargs:
 Here are a couple of things you should remember while working with Java
vargars:
1. While defining method signature, always keep varargs at last.
 The variable argument must be the last argument passed to the method. Let's
consider, you invoked doSomething() method like this:

Mrs. Divya Patel 116

58
04 -1 2 -2 0 2 4

Overloading Varargs Methods


 And, your doSomething() method is defined as:

 In this case, compiler cannot figure out the number of arguments passed to nums.

Mrs. Divya Patel 117

Overloading Varargs Methods


 The Java compiler assigns the first argument to p, and the remaining int
arguments are assigned to nums.
2. A method can have only one varargs parameter.
 For example, this method declaration is incorrect:

Mrs. Divya Patel 118

59
04 -1 2 -2 0 2 4

Overloading Varargs Methods


 Let’s consider you overloaded test() method like this:

Mrs. Divya Patel 119

Varargs and Ambiguity


 In the above program, the compiler gets confused if you try to invoke the
test() method even though test() methods are overloaded and accepts different
number of arguments.
 The compiler doesn’t know which method to call. The compiler may think, you
are trying to call test(int ... vargs) with one varargs argument. Also, the compiler
may think, you are trying to call test(int n, int ... vargs) with argument passed
to the first parameter with empty second parameter.
 Since there are two possibilities, it causes ambiguity. Because of this,
sometimes you may need to use two different method names instead of
overloading the varargs method.

Mrs. Divya Patel 120

60

You might also like