0% found this document useful (0 votes)
4 views22 pages

Java Module 2

Uploaded by

bharathbalaji701
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)
4 views22 pages

Java Module 2

Uploaded by

bharathbalaji701
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

Object-Oriented Programming with JAVA: BCS306A

MODULE II

MODULE II
Contents
Introducing Classes.

 Class Fundamentals.
 Demonstration of a Class Creation & assigning Objects Reference Variable
 Assigning Object Reference Variables
 Introducing Methods
 Constructors
 this Keyword
 Garbage Collection
Methods and Classes

 Overloading Methods
 Objects as Parameters, Argument Passing, Returning Objects
 Recursion
 Access Control
 Understanding static, Introducing the final keyword
 Introducing Nested and Inner Classes.

Introducing Classes

 The class is at the core of Java.


 It is the logical construct upon which the entire Java language is built because it
defines the shape and nature of an object.

Class Fundamentals

 Class defines a new data type. Once defined, this new type can be used to create
objects of that type.
 Thus, a class is a template for an object, and an object is an instance of a class.
Because an object is an instance of a class, you will often see the two words object
and instance used interchangeably.

The General Form of a Class

 When you define a class, you declare its exact form and nature. You do this by
specifying the data that it contains and the code that operates on that data.

 A class is declared by use of the class keyword

Department of Artificial Intelligence & Data Science, DBIT

1
Object-Oriented Programming with JAVA: BCS306A
MODULE II

 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.
 Variables defined within a class are called instance variables because each instance
of the class (that is, each object of the class) contains its copy of these variables.
 Thus, the data for one object is separate and unique from the data for another.

Syntax:
Class classname{
type instance variable1;
type instance variable2;
……….
type methodname(parameter – list){
//body of method
}
type mathodname(parameter – list){
//body of method
}
}

Creation of a Class & Declaring Objects to the Class

 Here is a class called Box that defines three instance variables: width, height, and
depth.
class Box{
double width;
double height;
double depth;}
 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.
 It is important to remember that a class declaration only creates a template; it does
not create an actual object
 Box mybox = new Box(); // create a Box object called mybox
 After this statement executes, mybox will be an instance of Box.
 Thus, it will have a “physical” reality.

Department of Artificial Intelligence & Data Science, DBIT

2
Object-Oriented Programming with JAVA: BCS306A
MODULE II

 Thus, every Box object will contain its copies of the instance variables 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.
For example, to assign the width variable of mybox the value 100, you would use the
following statement:
[Link] = 100;

Demonstration of a Class Creation & assigning Objects Reference Variable


public class Rectangle {
int length;
int breadth;
public static void main(String[] args) {
// Demonstration of - create 3 rectangles under the class
rectangle and calculate their area
Rectangle Rectangle1= new Rectangle();
Rectangle Rectangle2= new Rectangle();
[Link]=15;
[Link]=30;
[Link]=30;
[Link]=20;
[Link]("The Area of Rectangle1 is " +
([Link] * [Link]));
[Link]("The Area of Rectangle2 is " +
([Link] * [Link]));
//Demonstration of assignment operator for an object reference
variable
//All the length and breadth of Rectangle1 is assigned to
Rectangle3 and rectangle1’s length and breadth will remain
empty.
Rectangle Rectangle3 = Rectangle1;

[Link]("The Length of Rectangle3 is " +


[Link]);

Department of Artificial Intelligence & Data Science, DBIT

3
Object-Oriented Programming with JAVA: BCS306A
MODULE II

A Closer Look at new


As just explained, the new operator dynamically allocates memory for an object.

Declaring Objects

 When you create a class, you are creating a new data type.
 However, obtaining objects of a class is a two-step process.
 First, you must declare a variable of the class type. This variable does not define an
object. Instead, it is simply a variable that can refer to an object.
 Second, you must acquire an actual, physical copy of the object and assign it to that
variable. You can do this using the new operator.
 The new operator dynamically allocates (that is, allocates at run time) memory for an
object and returns a reference to it.
 This reference is, more or less, the address in memory of the object allocated by new.
This reference is then stored in the variable.
 Thus, in Java, all class objects must be dynamically allocated
 This statement combines the two steps just described. It can be rewritten like this to
show each step more clearly: Box mybox; // declare reference to object mybox = new
Box(); // allocate a Box object
 The first line declares mybox as a reference to an object of type Box.
 After this line executes, mybox contains the value null, which indicates that it does
not yet point to an actual object.
 Any attempt to use mybox at this point will result in a compile-time error. The next
line allocates an actual object and assigns a reference to it to mybox.
 After the second line executes, you can use mybox as if it were a Box object. But in
reality, mybox simply holds the memory address of the actual Box object.
Introducing methods

This is the general form of a method:

type name(parameter-list)
{
// body of method
}

Here, type specifies the type of data returned by the method. This can be any valid type,
including class types that you create.

Department of Artificial Intelligence & Data Science, DBIT

4
Object-Oriented Programming with JAVA: BCS306A
MODULE II

 If the method does not return a value, its return type must be void.
 The name of the method is specified by name. This can be any legal identifier other
than those already used by other items within the current scope.
 The 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.
 Methods that have a return type other than void return a value to the calling routine
using the following form of the return statement: return value;
 Here, value is the value returned.

Demonstration of Adding a Void Method To a Class


public class Box {
int length;
int width;
int breadth;
void volume() {
[Link]("The volume is
"+(length*width*breadth));
}
public static void main(String[] args) {
Box Box1 = new Box();
Box Box2 = new Box();
//With the above code we have created two Box objects
for the class.
[Link]=12;
[Link]=6;
[Link]=3;
[Link]=20;
[Link]=7;
[Link]=8;
[Link]();
[Link]();}}}

Output: The volume is 252, The volume is 960


Let us look closely at the above Program

 The first line here invokes the volume() method on Box1.

Department of Artificial Intelligence & Data Science, DBIT

5
Object-Oriented Programming with JAVA: BCS306A
MODULE II

 That is, it calls volume () relative to the Box1 object, using the object’s name
followed by the dot operator.
 Thus, the call to [Link]( ) displays the volume of the box defined by mybox1,
 There is something very important to notice inside the volume() method: the instance
variables width, height, and depth are referred to directly, without preceding them
with an object name or the dot operator.
 When a method uses an instance variable that is defined by its class, it does so
directly, without explicit reference to an object, and the use of the dot operator.
 This is easy to understand if you think about it. A method is always invoked relative
to some object of its class. Once this invocation has occurred, the object is known.

Demonstration of Adding a return Type Method to a Class


public class Box {
//Since we are storing a value inside the method, we will
not use the void method
int length;
int width;
int breadth;
int volume()
{return (length*width*breadth);

}
public static void main(String[] args) {
Box Box1= new Box(); //creating an object in the class
Box Box2= new Box ();
[Link]=3;
[Link]=3;
[Link]=3;
[Link]=2;
[Link]=4;
[Link]=5;
[Link]("The volume of first box is " +
[Link]());
[Link]("The volume of second box is "
+[Link]());

}
A Closer Look at the Program
 int volume(), to name a method with a return type answer the structure is
data type methodname().
There are two important things to understand about returning values:

Department of Artificial Intelligence & Data Science, DBIT

6
Object-Oriented Programming with JAVA: BCS306A
MODULE II

 The type of data returned by a method must be compatible with the return type
specified by the method. For example, if the return type of some method is Boolean,
you cannot return an integer.
 The variable receiving the value returned by a method (such as vol, in this case) must
also be compatible with the return type specified for the method.
Adding a Method That Takes Parameters
While some methods don’t need parameters, most do. Parameters allow a method to be
generalized.
 That is, a parameterized method can operate on a variety of data and/or be used in
several slightly different situations.
Demonstration of Class Creation by Adding a Method that takes Parameters
public class Box {
int length;
int breadth;
int width;
int volume() {
return (length* width*breadth);
}
//In the beneath line we have to use void since there is no
return answer in the method
void SetDim(int l, int b,int h) {
length=l;
breadth=b;
width = h;
}
public static void main(String[] args) {
Box Box1=new Box ();
Box Box2=new Box();
[Link](3,4,6);
[Link](12,14,16);
[Link]("The volume of First Box is "+
[Link]());
[Link]("The volume of Second Box is "+
[Link]());
}
}
Output: The volume of the First Box is 72
The volume of the Second Box is 2688

Department of Artificial Intelligence & Data Science, DBIT

7
Object-Oriented Programming with JAVA: BCS306A
MODULE II

A Closer Look at the Program


 First, we have created a method called volume(), where the calculation of volume
takes place. Since it is a return-type method, we defined it as
data type methodname().
 Next, we have created a method called SetDim(int l, int b, int h), which will
assign the values l, b, h to the instance variables length, breadth, and width.
 Through the class object Box1, using the code [Link](3,4,6) we will be
passing the values of length, breadth, and width to the corresponding object.

Constructors
In Java, constructors can be divided into 3 types:
 No-Arg Constructor.
 Parameterized Constructor.
 Default Constructor.
Let us understand the term Constructors

 It is called a constructor because it constructs the values at the time of object creation.
 It can be tedious to initialize all of the variables in a class each time an instance is
created.
 Even when you add convenience functions like setDim( ), it would be simpler and
more concise to have all of the setup done at the time the object is first created.
 Because the requirement for initialization is so common, Java allows objects to
initialize themselves when they are created.
 This automatic initialization is performed through the use of a constructor.
 A constructor initializes an object immediately upon creation.
 It has the same name as the class in which it resides and is syntactically similar to a
method.
 Once defined, the constructor is automatically called immediately after the object is
created before the new operator completes.
 Constructors look a little strange because they have no return type, not even void.
This is because the implicit return type of a class’s constructor is the class type itself.
 It is the constructor’s job to initialize the internal state of an object so that the code
creating an instance will have a fully initialized, usable object immediately.

Points to be remembered while creating a constructor

 Constructor name should be same as class name


 Constructor doesn’t have a return type.
 Through the constructor we are initializing the class object.

Department of Artificial Intelligence & Data Science, DBIT

8
Object-Oriented Programming with JAVA: BCS306A
MODULE II

 It is different from a method, but working is the same as that of a method.

No-Arg Constructor
The default constructor is as its name, if we do not create a constructor explicitly then
the Java compiler will create a default constructor. As a developer, if we create our
constructor with 0 arguments then it will be no argument constructor.
Parameterized Constructor
As the name suggests parametrized constructor in Java is a type of constructor that
takes one or more parameters as arguments. It is used to initialize the object with the values
passed by the user as the arguments while declaring the object.
Default constructor
The default constructor in Java is created by the compiler itself when the programmer
doesn't create any constructor. The purpose of the default constructor is to initialize the
attributes of the object with their default values.

Demonstration of a No – Arg Constructor


public class Box {
int length;
int width;
int breadth;
int volume;
Box() {
length=2;
width=3;
breadth=5;
}
int Volume() {
return (length*width*breadth);
}
public static void main(String[] args) {
Box Box1=new Box();
Box Box2=new Box();
[Link]("Volume of Box1 is "+ [Link]());
[Link]("Volume of Box2 is "+ [Link]());
}
}
/* Here the class called "Box" itself is acting as a method to
do the job. Here we have created two boxes with the same
dimension. */

Department of Artificial Intelligence & Data Science, DBIT

9
Object-Oriented Programming with JAVA: BCS306A
MODULE II

A Closer Look at the Program


 Here the class name Box should be the name of the constructor
 There is no parameter passed through the constructor, so this constructor is
acting as a no–arg constructor.
 Whenever a constructor is called the new object is initiated.
 You can use the same constructor to initialize the next object.
Parameterized Constructors
 While the Box( ) constructor in the preceding example does initialize a Box object, it
is not very useful—all boxes have the same dimensions.
 What is needed is a way to construct Box objects of various dimensions.
 The easy solution is to add parameters to the constructor.
Demonstration of class creation using a parameterized constructor
public class Box {
int length;
int width;
int breadth;
Box(int l, int w, int b){
length = l;
width =w;
breadth = b;
}
int volume() {
return (length * width * breadth);
}
public static void main(String[] args) {
Box Box1=new Box(2,3,4);
Box Box2=new Box (3,4,5);
[Link]("Volume of box1 is " +
[Link]());
[Link]("Volume of box2 is " +
[Link]());
}
}
A Closer Look at the Program
 Here we can see that the constructor Box is behaving like a method.
 Values of the instance variables will be taken thorough the parameters, when an object
is initiated.
The this keyword
 Sometimes a method will need to refer to the object that invoked it.
 To allow this, Java defines this keyword. this can be used inside any method to refer
to the current object

Department of Artificial Intelligence & Data Science, DBIT

10
Object-Oriented Programming with JAVA: BCS306A
MODULE II

Use of this Key word is


 this Key word helps to overcome shadowing or instance variable hiding.
 this Key word helps to call an overload constructor.
Demonstration of this keyword
public class ThisKeyWord {
int speed = 0;
int weight = 0;

// constructors
ThisKeyWord(){ // default
constructor.
}
ThisKeyWord(int speed){
// takes only one arg.
[Link] = speed;
}
ThisKeyWord(int weight, int speed) {
// takes two args.
[Link] = weight;
[Link] = speed;
}

public static void main(String[] args) {

ThisKeyWord obj1 = new ThisKeyWord (5, 6);


ThisKeyWord obj2 = new ThisKeyWord (10);

[Link]([Link]);
[Link]([Link]);
}

}
Instance Variable Hiding
 It is illegal in Java to declare two local variables with the same name inside the same
or enclosing scopes.
 Interestingly, you can have local variables, including formal parameters to methods,
which overlap with the names of the class’s instance variables.
 However, when a local variable has the same name as an instance variable, the local
variable hides the instance variable.
 We can use this keyword to resolve name–space collisions

Department of Artificial Intelligence & Data Science, DBIT

11
Object-Oriented Programming with JAVA: BCS306A
MODULE II

Garbage Collection
 Since objects are dynamically allocated by using the new operator, you might be
wondering how such objects are destroyed and their memory released for later
reallocation.
 Java takes a different approach; it handles deallocation for you automatically.
 The technique that accomplishes this is called garbage collection.
 It works like this: when no references to an object exist, that object is assumed to be
no longer needed, and the memory occupied by the object can be reclaimed.
 There is no explicit need to destroy objects as in C++.
 Garbage collection only occurs sporadically (if at all) during the execution of your
program.
 It will not occur simply because one or more objects exist that are no longer used.

A Stack Class
A stack is a linear data structure in which the insertion of a new element and
removal of an existing element takes place at the same end represented as the top of the
stack. To implement the stack, it is required to maintain the pointer to the top of the stack,
which is the last element to be inserted because we can access the elements only on the top
of the stack. Stack work with the LIFO principle.
LIFO (Last in First Out):
This strategy states that the element that is inserted last will come out first. You can
take a pile of plates kept on top of each other as a real-life example. The plate which we put
last is on the top and since we remove the plate that is at the top, we can say that the plate
that was put last comes out first. The stack can be considered as an example of
encapsulation.
Demonstration of Creation of A Stack class with numbers 1 to 10
import [Link];

public class NewStack {

public static void main(String[] args) {


Stack mystack1= new Stack();

for (int i=0; i<10; i++) {


[Link](i);
}
for (int i=0; i<10; i++) {

[Link]([Link]());

Department of Artificial Intelligence & Data Science, DBIT

12
Object-Oriented Programming with JAVA: BCS306A
MODULE II

}
}
OutPut:

9
8
7
6
5
4
3
2
1
0

Overloading Methods
In Java it is possible to define two or more methods within the same class that share the same
name, as long as their parameter declarations are different.

 When this is the case, the methods are said to be overloaded, and the process is
referred to as method overloading.
 Method overloading is one of the ways that Java supports polymorphism.
 When an overloaded method is invoked, Java uses the type and/or number of
arguments as its guide to determine which version of the overloaded method to
actually call.
 Thus, overloaded methods must differ in the type and/or number of their parameters.
 While overloaded methods may have different return types, the return type alone is
insufficient to distinguish two versions of a method.

Demonstration of Overloading Method


public class OvereLoadingOne {
void Test(){
[Link]("Just Printing is Happening");
}
void Test(int i)
{

Department of Artificial Intelligence & Data Science, DBIT

13
Object-Oriented Programming with JAVA: BCS306A
MODULE II

[Link]("The Square of the number is " +


(i*i));
}
void Test(int i, int j)
{
[Link]("The sum of the numbers is " +
(i + j));
}
void Test(int i, int j, int k)
{
[Link]("The product of the numbers is " +
(i*j*k));
}
public static void main(String[] args) {
OvereLoadingOne Object = new OvereLoadingOne();// We are
creating a class object in the main class
//Using the next line of codes, we are calling all the 4
functions we want to do through Test
//Here Test function is overloaded 4 times
[Link]();
[Link](3);
[Link](2,3);
[Link](2,3,4);
}
}

Overloading Constructors

 In addition to overloading normal methods, you can also overload constructor


methods. In fact, for most real-world classes that you create, overloaded constructors
will be the norm, not the exception.
 To understand why, let’s return to the Box class developed in the preceding chapter.
Following is the latest version of Box:

Demonstration of Overloading Constructors


public class Box {
// Demonstrating three constructors made in the overloading
method
int length;
int width;

Department of Artificial Intelligence & Data Science, DBIT

14
Object-Oriented Programming with JAVA: BCS306A
MODULE II

int breadth;
//In the below codes constructors are used when all
dimensions are specified
Box(int l, int w, int b){
length=l;
width=w;
breadth=b;
}
//constructors used when no dimensions are specified
Box(){
length=2;
width=3;
breadth=7;
}
//constructors used to calculate for a cube

Box(int l){
length=width=breadth=l;
}
int volume() {
return (length*width*breadth);
}

public static void main(String[] args) {


Box Box1=new Box(2,3,4);
Box Box2=new Box();
Box Box3=new Box (2);
[Link]("Volume of box1 "+
[Link]());
[Link]("Volume of box2 "+
[Link]());
[Link]("Volume of box3 "+
[Link]());

}
Using Object as Parameters
When you pass an object to a method, the situation changes dramatically, because
objects are passed by what is effectively call-by-reference. Thus, when you pass this
reference to a method, the parameter that receives it will refer to the same object as that
referred to by the argument. This effectively means that objects are passed to methods by use
of call-by-reference. Changes to the object inside the method do affect the object used as an
argument. For example, consider the following program.

Department of Artificial Intelligence & Data Science, DBIT

15
Object-Oriented Programming with JAVA: BCS306A
MODULE II

public class Box {


int width;
int height;
int depth;
Box(Box obj){// passing the object of the box through a
constructor
width=[Link];
height=[Link];
depth=[Link];
}
Box(int w, int h, int d){// constructor with parameters to
access the values
width=w;
height=h;
depth=d;
}
Box(){// No arg constructor, passing the measurements
separately
width= 2;
height=3;
depth=4;
}
Box(int l){// constructor, passing only one measurement,
where all measures are the same
width=height=depth=l;

}
int volume() {
return width*height*depth;
}

}
public class OverloadDemo {

public static void main(String[] args) {


Box mybox1=new Box(10,20,30);
Box mybox2=new Box(10);
Box cube= new Box(3);
Box noarg=new Box();
[Link]("Using Parameter - constructor "
+ [Link]());
[Link]("Using one Parameter -
constructor " + [Link]());
[Link]("Using Parameter-Cube -
constructor " + [Link]());

Department of Artificial Intelligence & Data Science, DBIT

16
Object-Oriented Programming with JAVA: BCS306A
MODULE II

[Link]("Using no-arg - constructor " +


[Link]());
//Next demonstrate how we pass an object as a parameter
Box copy= new Box(mybox1); // Created a copy of
mybox1 object
Box mybox3= new Box(mybox1); /* Created a box object by
passing an object through
the constructor*/
[Link]("By passing object through
constructor " + [Link]());
}

}
A closer Look at the program
 First, we have constructed a class called Box
 In that we have demonstrated how we will pass the values through the constructor as
in the previous program.
 Using the code Box(Box obj) we are passing the values through the object of that
class
 Next, we have constructed a new class called OverloadDemo to test whether all the
overloading method works.
 To pass the values through the object we have created a copy of the object using the
code Box copy= new Box(mybox1) and passed this new object copy through the
constructor using the code Box mybox3= new Box(mybox1).

Returning Objects
A method can return any type of data, including class types you create. For example,
in the following program, the increByten() method returns an object in which the value of a is
ten greater than it is in the invoking object.
public class Test {
int a;
Test(int i){
a=i;
}
Test incr() {
Test obj= new Test(a+10);
return obj;
}
public static void main(String[] args) {
Test obj1=new Test(2);
Test obj2;
obj2=[Link]();

Department of Artificial Intelligence & Data Science, DBIT

17
Object-Oriented Programming with JAVA: BCS306A
MODULE II

[Link](obj1.a);
[Link](obj2.a);
}
}
A closer look at the program
 Each time increByten() is invoked, a new object is created. And a reference to it is
returned to the calling function.
 Since all the objects are dynamically allocated using new, you don’t need to worry
about an object is 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, the
object will be reclaimed the next time garbage collection takes place.

Recursion
 Java supports recursion. Recursion is the process of defining something in terms of
itself. As it relates to Java programming, recursion is the attribute that allows a
method to call itself.
 A method that calls itself is said to be recursive.
 The classic example of recursion is the computation of the factorial of a number. The
factorial of a number N is the product of all the whole numbers between 1 and N.
 For example, 3 factorial is 1 × 2 × 3, or 6. Here is how a factorial can be computed
by use of a recursive method:

// A simple example of recursion – To calculate Factorial of a Number


public class Factorial {
int i;

int result;
int cal(int n) {
if (n==1) return 1;
result=cal(n-1)*n;
return result;
}
public static void main(String[] args) {
Factorial object1= new Factorial();
[Link]([Link](3));
[Link]([Link](6));
}
}
A Closer Look at the Program
 When a method calls itself, new local variables and parameters are allocated storage
on the stack, and the method code is executed with these new variables from the start.

Department of Artificial Intelligence & Data Science, DBIT

18
Object-Oriented Programming with JAVA: BCS306A
MODULE II

 As each recursive call returns, the old local variables and parameters are removed
from the stack, and execution resumes at the point of the call inside the method.
Introducing Access Control
 encapsulation provides another important attribute: access control.
Through encapsulation, you can control what parts of a program can access the
members of a class.
 By controlling access, you can prevent misuse. For example, allowing access to data
only through a well-defined set of methods, you can prevent the misuse of that data.

Java’s access specifiers - public, private, and protected.


Public Access Modifiers - If a class is declared as public then we can access that
class from anywhere.

Protected Access Modifier - This modifier can be applied to the data member,
method, and constructor, but this modifier can’t be applied to the top-level classes and
interface. A member is declared as protected as we can access that member within the
current package and only in the child class of the outside package.

Private Access Modifiers - This modifier is not applicable to top-level classes or


interfaces. It is only applicable to constructors, methods, and fields inside the classes. If a
variable, method, or constructor is declared as private then we can access them only from
within the class i.e., from outside the class we can’t access them.

Introducing the keyword final


A field can be declared as final. Doing so prevents its contents from being
modified, making it essentially, a constant This means that you must initialize a final
field when it is declared.
Example: final int x=30; by doing this we cannot assign any new value to x.

Introducing Nested and Inner Classes


It is possible to define a class within another class, such classes are known as nested
inner classes.

 The scope of a nested inner class is bounded by the scope of its enclosing class.
 Thus, if class B is defined within class A, then B does not exists independently of A.
 A nested class has access to the members, including private members, of a class in
which it is nested.
 However, the enclosing class does not have access to the members of the nested class.

Department of Artificial Intelligence & Data Science, DBIT

19
Object-Oriented Programming with JAVA: BCS306A
MODULE II

 A nested class that is declared directly within its enclosing class scope is a member of
its enclosing class.
 It is also possible to declare a nested class that is local to a block.

Different Types of Nested Class – Static & Non-Static


Static Nested Class

 A static nested class is one that has the static modifier applied.
 Because it is static, it must access the non static members of its enclosing class
through an object. That is, it cannot refer to non – static members of its
enclosing class directly. Because of this restriction, static nested classes are
seldom used.

Non-Static Nested Class – Inner Class

 The most important type of nested class is the Inner Class.


 An Inner class is a non-static nested class.
 It has access to all of the variables and methods of its outer class and may
refer to them directly in the same way that other non-static member of the
outer class does.

Different Types of Non-static nested class (inner class)

 Member inner class


 Anonymous inner class
 Local inner class

Class Type Description


Member Inner Class A class created within the class and
outside method.
Anonymous Inner Class A class created for implementing an
interface or extending a class. The
Java compiler decides its name.
Local Inner Class A class was created within the
method.

Department of Artificial Intelligence & Data Science, DBIT

20
Object-Oriented Programming with JAVA: BCS306A
MODULE II

Advantages of Java Inner Classes

 Nested classes represent a particular type of relationship that is it can access all the
members (data members and methods) of the outer class, including private.
 Nested classes are used to develop more readable and maintainable code because it
logically groups classes and interfaces in one place only.
 Code Optimization: It requires less code to write.

Need Of Inner Classes

Sometimes users need to program a class in such a way that no other class can access
it. Therefore, it would be better if you included it in other classes. If all the class objects are a
part of the outer object, then it is easier to nest that class inside the outer class. That way all
the outer class can access all the objects of the inner class.

Demonstration of Nested Inner Classes

Here all the classes are above the main methods. So, it will come under the category
of Member Inner Class. Demonstrating that all inner classes can access all outer class data
and objects. Also, a Private variable can be accessed by the inner class created by an outer
class and defined as a private variable as data.

class OuterClass {

private int data=30;


//In the next lines create a class called Inner inside the
OuterClass and one method called msg() inside it.
class Inner{
void msg()
{[Link]("data is "+data);
}
}
public static void main(String[] args) {
OuterClass outerobj=new OuterClass(); //creating an
outer class object
[Link] innerobj=[Link] Inner();
//creating one inner class object and accessing data
[Link]();

}
}

Department of Artificial Intelligence & Data Science, DBIT

21
Object-Oriented Programming with JAVA: BCS306A
MODULE II

A Closer Look at the Program


 Created a class called OuterClass.
 Defined data as a private variable for the class OuterClass.
 Defined an inner class called Inner inside the OuterClass
 These classes are created before the main Method. So it is the Member Inner Class
category
 Under the main method created the objects for the outer class and inner classes.

Department of Artificial Intelligence & Data Science, DBIT

22

You might also like