Java – Nested class

Java – Nested class 2017-06-13T00:04:37+00:00

nested class :

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.

That means, if class B is defined within class A, then B is known to A, but not outside A.

If A is nesting class B, then A has access to all the members of B, including private members. But the B does not have access to the members of nested class.

There are two types of nested classes:

1.      Static

2.      Non – Static

Static nested class

A static nested class is one which has the static modifier, as it is static it must access the member of its enclosing class through an object.

That means it cannot refer to member of its enclosing class directly.

Non – Static nested class

Non – Static nested class is known as inner class.

It has access to all of its variables and methods of its outer class and can refer to them directly.

An inner class is fully within the scope of its enclosing class.

EX :


 


Output :
Shipped 16 item(s) to Congo
Let us see one more example but here the program will not compile

Here, y is declared as an instance variable of Inner. Thus it is not known outside of

that class and it cannot be used by showy( ).

Prev Next