Nested class demo program
The Java programming language allows you to
define a class within another class. Such as that class is known as nested
class.
Syntax:
class OuterClass{
. .
.
class InnerClass{
. . .
}
}
Example:
OUTPUT:
Nested classes are divided into
two categories: static and non-static. Nested classes that are declared
static
are called static nested classes. Non-static nested classes are called inner classes.
Syntax:
class OuterClass {
...
static class StaticNestedClass {
...
}
class InnerClass {
...
}
}
...
static class StaticNestedClass {
...
}
class InnerClass {
...
}
}
Inner class have access to other members
of the enclosing class, if they are declared private. Static nested
classes do not have access to other members of the enclosing class.
As a member of the
OuterClass
, a nested class can be declared private, public protected
Non-Static
nested class Syntax:
class OuterClass{
. .
.
class InnerClass{
. . .
}
}
Static
nested class Syntax:
class OuterClass{
. .
.
static class InnerClass{
. . .
}
}
Non static
nested class example:
Already declare above.
Static nested
class example:
OUTPUT:
If we use static or non-static nested class then the main
different is how to declare object. Below the description:
Non-static
nested class:
OuterClass o1= new OuterClass();
OuterClass.InnerClass obj= o1.new InnerClass();
Static nested
class:
OuterClass.InnerClass obj= new OuterClass.InnerClass();
0 comments: