Java Inner Classes | Nested Classes

–Section––Content–
Part 1: Nested Class Types & BenefitsBasic Syntax, Types of Nested Classes and Benefits
Part 2: Nested Class Object CreationCreate Objects of – Inner Class, Static Nested Class, Local Class, Anonymous Class
Part 3: Nested Class Member AccessAccess Members in Outer Class, Inner Class, Static Nested Class, Local Class, Anonymous Class
Part 4: Lamda ExpressionsSyntax and Examples of Lamda Expressions
[SQL and TSQL Queries]SQL and TSQL Queries Cheat Sheet

[Download Java Google Sheet + Project Files ]

Part 1: Nested Class Types and Benefits

Nested Class TypeJava CodeExplanation
Nested Classclass OuterClass {
    …
    
class NestedClass {
        …
    }
}
Nested Class – define a class within another class
Types of Nested ClassNested Class
——-> Static Nested Class
——-> (Non-Static) Inner Class
            ———> Local Class
            ———> Anonymous Class
            ———> Lamda Expression
Static Nested Classclass OuterClass {
  …
  
static class StaticNestedClass {
    …
  }
}
Nested classes that are declared static are called static nested classes.
Non-Static Nested Class

Inner Class
class OuterClass {
  …
  
class InnerClass {
    …
  }    
}
Non-static nested classes are called inner classes.
Local Classclass OuterClass {
    …
    
public void method() {
        …
        
class LocalClass {
            …
        }    
    }
}
Local Class is declared as an inner class within the body of a method or any block
Anonymous Classclass OuterClass {
    …
    interface OuterIntf() {…}

    
public void method() {
        …
        OuterIntf anonObject = new OuterIntf() {
            …
        }    
    }
}
Anonymous Class is declared as an inner class within the body of a method without naming the class.
Benefits of Nested ClassLogical Placement:
If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together.

Encapsulation / Hiding:
Nested class can access the private members of the outer class.

So private members of outher class can be kept hidden from outside but visible to nested classes.

The nested class itself can be kept hidden from outside.

Part 2: Inner Class | Static Nested Class | Local Class | Anonymous Class – Object Creation

Nested Class TypeJava CodeExplanation
Create Inner Class Objects
public
class OuterClass {
  …
  
class InnerClass {
    …
  }

  public void create() {
    
//Option 2: create inner class from
    //an instance method of outer class


    
OuterClass.InnerClass innerObject =
    
this.new InnerClass();
  }

  public
static void main() {
    
//Option 1: create inner class object from
    //static method of outer class

    OuterClass outerObject =
    new OuterClass();

    
OuterClass.InnerClass innerObject =
    outerObject.
new InnerClass();
  }
    
}
Inner class (non-static) is associated with an instance of its outer class.

An instance of InnerClass can exist only within an instance of OuterClass
Create Static Nested Class Objectsclass OuterClass {
  …
  
static class StaticNestedClass {
    …
  }

  public static void main() {
    
//create static class object from any method

    StaticNestedClass staticNestedObject =
    new StaticNestedClass();

  }

}
Static nested class is associated with its outer class (without ouer instance).


Create Local Class Objects
class OuterClass {
  …

  public void localMethod() {


    class LocalClass {
      …
    }

    
//create local class object from  
    //an instance method of outer class

    
LocalClass localObject = new LocalClass();
  }

  public
static void main() {
    
//cannot directly create local class object
    //from outside local method

    OuterClass outerObject =
    new OuterClass();

    outerObject.
localMethod();
  }
    
}
Local class is associated with a method of its outer class instance.

Create Anonymous Class Objects
class OuterClass {
  …
  
interface Anonymous {
    public void printMembers();
  }

  public void
localMethod() {
    //create anonymous class object
    //by implementing interface
    Anonymous anonymousObject = new Anonymous() {
      …
    }
    anonymousObject.printMembers();
  }

  public
static void main() {
    OuterClass outerObject = new OuterClass();
    outerObject.
localMethod();
  }
    
}
Anonymous class is associated with a method of its outer class instance.

Part 3: Member Access for Nested Classes

Nested Class TypeJava CodeExplanation
Access for Inner Classpublic class OuterClass {

  String outerField = “outer”;
  static String staticOuterField = “static outer”;

  
class InnerClass {
    void accessMembers() {
      System.out.println(outerField);
      System.out.println(staticOuterField);
    }
  }

  
public static void main(String[] args) {
    OuterClass outerObject = new OuterClass();
    OuterClass.InnerClass innerObject =
    outerObject.new InnerClass();
    innerObject.accessMembers();            
  }
}
Inner class has direct access to

1. all the outer class object’s members
— both static and instance members.
— both private and public members
2. the inner class object’s members
3. static inner class members not allowed in Java 8


OUTPUT
————
outer
static outer
Access for Static Nested Classpublic class OuterClass {

  String outerField = “outer”;
  static String staticOuterField = “static outer”;

  
static class StaticNestedClass {
    void accessMembers(OuterClass outer) {
      
// Compiler error: non-static field
      // System.out.println(outerField);

            
      System.out.println(outer.outerField);
      System.out.println(staticOuterField);
    }
  }

  
public static void main(String[] args) {
    OuterClass outerObject = new OuterClass();
    StaticNestedClass staticNestedObject =
    new StaticNestedClass();        
    staticNestedObject.accessMembers(outerObject);
  }
}
Static nested class has direct access to
1. static members of outer class
2.
no direct access to instance members of outer class
3. can access instance variables of outer class only through an object reference.
4. members of static nested class



OUTPUT
————
outer
static outer
Access for Local Classpublic class OuterClass {

  String outerField = “outer”;
  static String staticOuterField = “static outer”;

  
public void outerMethod(String localParameter) {
    String localMethodString = “local method”;
    
class LocalClass {
      
void printMembers() {
        SOP(outerField);
        SOP(staticOuterField);
        SOP(localMethodString);
        SOP(localParameter);
      }
    }

    //create local class object
    LocalClass localObject = new LocalClass();
    localObject.printMembers();
  }

  public static void main(String[] args) {
    OuterClass outerObject = new OuterClass();
    outerObject.outerMethod(“outer parameter”);
  }
}
Local class has direct access to

1. all the outer class object’s members
— both static and instance members.
— both private and public members
2. the local method variables that are final
3. the local method parameters
4. the local class object’s members
5. static members are not allowed in local classes



OUTPUT
————
outer
static outer
local method
local parameter
local class
Access for Anonymous Classpublic class OuterClass {

  String outerField = “outer”;
  static String staticOuterField = “static outer”;

  
interface Anonymous {
    public void printMembers();
  }

  
public void outerMethod(String localParameter) {
    String localMethodString = “local method”;
    
Anonymous anonymousObject = new Anonymous() {
      
public void printMembers() {
        SOP(outerField);
        SOP(staticOuterField);
        SOP(localMethodString);
        SOP(localParameter);
      }
    }

    anonymousObject.printMembers();
  }

  public static void main(String[] args) {
    OuterClass outerObject = new OuterClass();
    outerObject.outerMethod(“outer parameter”);  
  }
}
Anonymous class has direct access to

1. all the outer class object’s members
— both static and instance members.
— both private and public members
2. the local method variables that are final
3. the local method parameters
4. the local class object’s members
5. static members are not allowed in static nested classes



OUTPUT
————
outer
static outer
local method
local parameter
local class

Part 4: Lamda Expressions – Syntax and Examples

Nested Class TypeJava CodeExplanation
Lamda ExpressionWhat? Lamdas are used in a special case of Anonymous class that implement an interface with a single method.

Why? Lambda expressions allows you to implement express instances of single-method classes more compactly.
Lamda Syntaxclass OuterClass {
    …
    interface OuterIntf() {…}

    
public void method() {
        …
        OuterIntf lamdaObject = () -> {
            …
        }    
    }
}
1. we skip the new keyword
2. we skip the interface method statement
3. since there is only one method in the intf
4. () will have the parameters of the method
5. we can skip the type of arguments inside ()
6. {} will have the implementation of the method
7. we can skip { and } if there is only one statement in the method implementation
Lamda Accesspublic class OuterClass {

  String outerField = “outer”;
  static String staticOuterField = “static outer”;

  
interface Anonymous {
    public void printMembers();
  }

  
public void outerMethod(String localParameter) {
    String localMethodString = “local method”;
    
Anonymous lamdaObject = () -> {
        SOP(outerField);
        SOP(staticOuterField);
        SOP(localMethodString);
        SOP(localParameter);
    }

    lamdaObject.printMembers();
  }

  public static void main(String[] args) {
    OuterClass outerObject = new OuterClass();
    outerObject.outerMethod(“outer parameter”);  
  }
}
Lamda expression is just a shorthand notation for creating anonymous classes that implement interface with a single method.

So access properties are same as anonymous methods
Lamda Examplespublic class OuterClass {

  
interface Printer {
    public void printMembers(String memberType);
  }

  
//lamdas can be used in different ways
  Printer lamdaObject1 = (memberType) -> {
    System.out.println(“memberType: “+memberType);
  };

  Printer lamdaObject2 = (String memberType) -> System.out.println(“memberType: “+memberType);

  Printer lamdaObject3 = memberType -> System.out.println(“memberType: “+memberType);

  lamdaObject1.printMembers(“small biz owner”);
  lamdaObject2.printMembers(“large biz owner”);
  lamdaObject3.printMembers(“millinare biz”);

[Download Java Google Sheet + Project Files ]

Leave a Reply

Your email address will not be published. Required fields are marked *