Inner Classes
- Eclipse: Oxygen
- Java: 1.8
Here in Java Inner classes is the concept where we want to add more encapsulation to the given code. When we declare a class inside a class then the inside class can access all the private members in addition to the inner class can be hidden from the outside world.
Also, it is logical to group two classes that are related together.
Types of inner class in java.
- Nested Inner class
- Method Local Inner class
- Anonymous Inner class
- Static Inner class
In this tutorial, we will discuss non-static inner classes.
In the following example, the lock is an inner class. Within the lock class, we have initialized the Boolean variable. Then we create a constructor method. Within the method, we create the object of the lock class, and then invoke the getLock() method. setLock() in the reference variable like shopStatus().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
public class Door { private Lock lock; public Door(){ lock = new Lock(true); } public Lock getLock() { return lock; } public void shopStatus(){ if(lock.isLock()){ System.out.println("Shop is closed, please visit later."); }else { System.out.println("Welcome, we are open."); } } public class Lock { private boolean lock; public Lock(boolean lock) { this.lock = lock; } public boolean isLock() { return lock; } public void setLock(boolean lock) { this.lock = lock; } } } |
1 2 3 4 5 6 7 8 9 10 |
public class Shop { public static void main(String[] args) { Door door = new Door(); door.shopStatus(); door.getLock().setLock(false); door.shopStatus(); } } |
Output
1 2 |
Shop is closed, please visit later. Welcome, we are open. |
Contributed by: Poonam Tomar