Nestedclass,nested Interface
Nestedclass,nested Interface
In Java, it is possible to define a class within another class, such classes are known
as nested classes. They enable you to logically group classes that are only used in one
place, thus this increases the use of encapsulation, and creates more readable and
maintainable code.
• The scope of a nested class is bounded by the scope of its
enclosing class. Thus in below example, class NestedClass does
not exist independently of class OuterClass.
• A nested class has access to the members, including private
members, of the class in which it is nested. But the enclosing class
does not have access to the members
of the nested class.
• A nested class is also a member of its enclosing class.
• As a member of its enclosing class, a nested class can be
declared private, public, protected, or package private(default).
Syntax:
class OuterClass
{
-----
...
public class NestedClass
{
----
...
}
}
// outer class
class OuterClass
{
// static member
static int outer_x = 10;
// instance(non-static) member
int outer_y = 20;
// private member
private static int outer_private = 30;
}
}
}
// Driver class
public class StaticNestedClassDemo
{
public static void main(String[] args)
{
// accessing a static nested class
OuterClass.StaticNestedClass nestedObject = new
OuterClass.StaticNestedClass();
nestedObject.display();
}
}
Output:
outer_x = 10
outer_private = 30
Inner classes
To instantiate an inner class, you must first instantiate the outer class. Then,
create the inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
// outer class
class OuterClass
{
// static member
static int outer_x = 10;
// instance(non-static) member
int outer_y = 20;
// private member
private int outer_private = 30;
// inner class
class InnerClass
{
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);
}
}
}
// Driver class
public class InnerClassDemo
{
public static void main(String[] args)
{
// accessing an inner class
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new
InnerClass();
innerObject.display();
}
}
Output:
outer_x = 10
outer_y = 20
outer_private = 30
// Interface
interface Age {
// Class 1
// Helper class implementing methods of Age Interface
class MyClass implements Age {
// Class 2
// Main class
// AnonymousDemo
class GFG {
// Main driver method
public static void main(String[] args)
{
// Class 1 is implementation class of Age interface
MyClass obj = new MyClass();
Output:
Age oj1 = new Age()
{
@Override
public void getAge()
{
System.out.print("Age is " + x);
}
};
// Interface
interface Age {
int x = 21;
void getAge();
}
// Main class
class AnonymousDemo {
oj1.getAge();
}
}
Output
Age is 21