Nested classes in java || What are nested classes in java? || Explain nested classes in java.



Nested Classes


It is possible to define a class within another class; such classes are known as nested classes. The scope of a nested class is bounded by the scope of its enclosing class. Thus, if class B is defined within class A,ate members, of the class in which it is nested. However, the enclosing class does not have access to the members of the nested class.

There are two types of nested classes: static and non-static.

static:

A static nested class is one which has the static modifier applied. Because it is static, it must access the members of its enclosing class through an object then B is known to A, but not outside of A. A nested class has access to the members, including private. That is, it cannot refer to members of its enclosing class directly. Because of this restriction, static nested classes are seldom used.

Non-static:


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 members of the outer class do. Thus, an inner class is fully within the scope of its enclosing class.

Example:

class Outer
{
private String msg;
Outer (String msg) //Constructor of Outer
{ this.msg = msg; }
void outerShow()
{
Inner objInner = new Inner();
objInner.show();
}
class Inner
{
void show()
{ System.out.println(msg); }
}
}
class Test
{
public static void main(String args[])
{
Outer testObj = new Outer("Hello M");
testObj.outerShow();
}
}

1 Comments

Please do not enter any spam link in the comment box

Post a Comment

Please do not enter any spam link in the comment box