static nested class, Member inner class, Local class & Anonymous class

Nested classes lets you define one class within another. Just the same way classes can have member methods and variable , a class can also have a member class.

Before we start why do we need to have a class inside another class. As a OO programer we know that in one class we will have code specific to an object and nothing else !! isn’t it. We are professionals now in maintaining cohesion :-), hopefully you also feel the same !!

Let’s take situation where you do have specialized in a class but  some behaviour need to be moved to more specialized class but it’s still intimately tied to the class which you are already designing it. nested classes are the way to go.

For example,

Lets say you are designing a class called DbAdapter which got behaviours to open & close the connection to database. It also contains behaviours which are responsible to insert, delete & update data database. Now you tell me, does it makes sense to move open() and close() methods to another class ?

But those behaviour are still intimate with the other behaviours isn’t it ?

That’s where exactly we use nested class. We will create a new private class called DbHelper and we will move open() and close() method to this nested class. We still get have our cohesion within the class 🙂

So, let’s move forward with this concept..

Write down the below tree which contains the classification of Nested classes

As we can see in the above figure there are two type of nested class.

  1. static nested class
  2. non-static nested class ( aka inner class)

static nested class, Member inner class & Local class :

video

Anonymous inner class :

video


Inner classes

Inner classes :