5. Inner Outer Class - mStylias/JavaTopics GitHub Wiki

Definitions

Inner class: A class that is contained inside another class
Outer class: A class that is not contained inside another class

Inner class characteristics

Inner classes can:

  • Be either private or public
  • Be static or non-static
  • Access private fields of their respective outer class

Inner classes can not

  • Be created if their outer class is not instantiated

Inner class special types

Method-local Inner Class

In Java, we can write a class within a method and this will be a local type. Like local variables, the scope of the inner class is restricted within the method.
A method-local inner class can be instantiated only within the method where the inner class is defined.

Anonymous Inner Class

An inner class declared without a class name is known as an anonymous inner class. In case of anonymous inner classes, we declare and instantiate them at the same time. Generally, they are used whenever you need to override the method of a class or an interface.

General inner class structure

Example implementation details

In this example we built onto the car class from the 4. Constructors example.
A class is created inside the car named Engine. In this scenario Car is the outer and Engine is the inner class.
Inside the calculateEnvironmentalImpact method of the engine class we created a class named ImpactCalculator to demonstrate the method-local inner class. In the Main class an abstract class is created to be implemented in a way that showcases the anonymous inner class

Sources and more information

https://www.tutorialspoint.com/java/java_innerclasses.htm#:~:text=In%20Java%2C%20just%20like%20methods,is%20called%20the%20outer%20class.&text=Following%20is%20the%20syntax%20to%20write%20a%20nested%20class.
https://www.w3schools.com/java/java_inner_classes.asp