Local inner class
- Eclipse: Oxygen
- Java: 1.8
Working with the local inner class which is defined or structured inside the outer class is shown here. Here the example of door and lock is shown as a real-life example.
In Java, we can write a class within a method it is called a local inner type. Like local variables, the scope of the inner class is restricted inside the method. If you want to invoke the methods of a local inner class, you must instantiate this class inside the method.
The advantage of such a case is the inner class is completely hidden from the outside world.
The syntax for writing an inner class is shown below.
1 2 3 4 5 6 |
public class Door { public boolean isLocked(String key) { class Lock { } } } |
Here, the class Door is the outer class and the class Lock is the local inner class. We access the class through a method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class Door { public boolean isLocked(String key) { class Lock { public boolean isLocked(String key) { if (key.equals("qwerty")) { return false; } else { return true; } } } return new Lock().isLocked(key); } } |
1 2 3 4 5 6 7 8 9 |
public class Shop { public static void main(String[] args) { Door door = new Door(); System.out.println(door.isLocked("test")); } } |
If the user enters the correct key and executes the following program, then the output would be false; otherwise, the user will get the output.
Output
true
Contributed by: Poonam Tomar