首页 > 代码库 > Java Nested Class

Java Nested Class

Normal class(Non-nested class) can only be public, abstract or final. For nested classes, static is allowed.

 

Nested classes(private, public, protected) -> 2 Categories.

1. Static Nested Class (Very Different from C# static class)

alpha: Have access to all the static members of its parent class.

beta: Can instantiate objects by new ParentClass.StaticNestClass(). Now allowed to create objects in C#. 

gamma: Can have non-static members.

delta: same as gamma. Cannot access ParentClass.this.

 

2. Non-static nested class(Inner Class)

alpha: Have access to all the members of its parent class.

beta: Can instantiate objects by new ParentClass().new InnerClass().

gamma: Cannot have static members, except for final static fields.

delta: Variable shadowing:

    ParentClass.this.memberName -> Parent class member.

    this.memberName, ParentClass.InnerClass.this.memberName  -> Inner class member

 

 

======================================

1. Interface can only be defined inside a top-level class, an interface or in static context because interfaces are inherently static.

2. Anonymous Classes:

  Interface/AbstractClass obj = new Interface/AbstractClass(Empty for interface. Initialize for abstract class){

  String/int ...;

  public void ImplementAbstractMethodA(){...}

  public void ImplementAbstractMethodB(){...}

}; <--Semicolon in the end

Java Nested Class