Top 20 Advanced Java Questions on Anonymous Class, Nested Static and Inner Class for Interviews

Hello guys, static class and nested classes are one of the tricky topic to master in Java and that's why they are quite popular on Java Interviews. Not many Java developer knows about Anonymous class or how Lambda is compiled into Anonymous class by JVM etc. If you are going for Java Interview, I highly recommend you to prepare nested class topic well in Java. Just like in the past, I have shared many Java in-depth questions on different topics like Lambda Expression, Stream API, Generics, Collections, Multithreading, String, array, Design Patterns, OOP, Spring Framework, Hibernate etc,

In this article, I am going to share 20 questions related to nested classes in Java. This covers both static and non-static nested class as well Anonymous class in Java. You can go through these questions to quickly revise this important topic.



20 Nested Class Interview Questions for Java Developers

Without wasting anymore of you time, here is a list of common nested class, Inner class and Anonymous class based questions for Java Interviews. If you have worked in Java then most likely you will know the answer of these questions but if you haven't these questions are will encourage you to learn them. 


1. What is nested class in Java?

Any class which is declared inside another class is called a nested class in Java. Yes, its possible to declare a class inside another class in Java. If you declare then the class which enclose other class is known as top level class and the class which are declared inside top level class is known as nested class in Java. 

Here is an example of nested class in Java:

public class Main {
    public class InnerClass {
        private int count = 0;
        
        public int getCount(){
            return count;
        }
    }
    
    public  static class NestedClass {
        private String version = "1.0.0";
        
        public String getVersion(){
            return version;
        }
    }

}


In this example, Main is a top level class and there are two nested classes, known as InnerClass and NestedClass, one is non-static while other is static. This simple declaration of static nested class makes a big difference when it comes to using it.

For example, if you want to call the getVersion() method from NestedClass you need to create an instance of NestedClass but which is easier than creating an Instance of InnerClass to call getCount() method because inner classes are associated with an object of top level class, you can see this tutorial to learn how to use nested class in Java



2. What is Inner class in Java?

Inner class and nested class are commonly used interchangeably to refer a class which is declared inside another class by many programmers. But, precisely, a non-static nested class is better known as Inner class in Java.  

Here is a diagram which illustrate different types of nested classes in Java, including inner, local and Anonymous class.

Top 20  Static Nested and Non Static Inner class in Java Interview questions



3. What is difference between static and inner class in Java?

As the name suggest, a static nested class has static word in it while Inner class is a non-static member of the class. This means you cannot use Inner class inside a static context in Java. This is similar to calling a non-static method inside a static method in Java?


4. What is Anonymous class in Java?

A class which is declared and used without any name is called Anonymous. This is like a temporary or throw away class which you need only for a particular line of code. One of the popular example of Anonymous class is to implement an interface like Runnable or Callable or extending a Thread class as shown below:

public class Main {

public static void main(String args[]){
  Thread workerThread = new Thread(){
      public void run(){
          System.out.println("Worker thread is running");
      }
  };
  
  workerThread.start();
}

In this case, when we create new Thread(), we create an Anonymous class which extends Thread class and implement its run() method. If you remember, Thread's run() method is empty, hence if you want to do something useful, you need to extend Thread and implement its run() method and that's what this Anonymous class is doing here.

Though, from Java 8 onwards, you can easily replace Anonymous class with Lambda expression as shown in the given example. Your IDE like IntelliJ IDEA can also do this for you with helpful hints. 


5) What is local class in Java?

Any class which is declared inside a block is a local class in Java.


6) How to create object of inner class in Java?

You need object of Enclosing class to create an object of Inner class in Java


7) Can you access non-static members of enclosing class inside a static nested class?

No, you cannot access non-static members of top level class inside a nested static class in Java. 


8) Can you access private members of outer class inside nested class in Java?

Yes, private members are accessible inside nested class in Java 


9) Can you access a non-final local variable inside Anonymous class in Java?

No, non-final local variable are not accessible inside Anonymous class but this has been changed with Lambda, now you can access a effectively final variable inside Lambda. Effectively final means a variable which has not changed inside the block. 


10) Can a Inner class contain static variables in Java?

Yes, Inner class may contain static variables in Java as shown in following example, you can see that count is static variable inside an Inner class in Java and program compile and runs fine:

public class Main {
    
    private class Inner{
        private static int count;
    }

public static void main(String args[]){
  Thread workerThread = new Thread(){
      public void run(){
          System.out.println("Worker thread is running");
      }
  };
  
  workerThread.start();
}

}


11) Can you access all members of enclosing class inside an inner class in Java?

Yes, inner class can access all members of enclosing class including private members.  Here is an example to prove this point. You can see that age is private member variable of Main class which is the Enclosing class here and Inner class can access it without any fuss. 

public class Main {
    private int age;

    private class Inner{
        private static int count;

       public boolean isAdult(){
          return age > 18; 
       }
    }

public static void main(String args[]){
    // main code
}

}


12) What is difference between static and non-static nested class in Java?

its the same as we discussed between static vs inner class, you can read my earlier article about difference between static and non-static nested class in Java to learn more. 


13) Can you declare a local inner class private, public or protected in Java?

14) What is the use of nested class in Java?

15) What is the use of member inner class in Java?

16) Why using a nested static class is better than non-static nested class?


17. What is the use of Anonymous class in Java?

Before Lambda was born, Anonymous class was the only way, you can pass dynamic code to a function or method in Java. For example, Collections.sort() method accept a Comparator, a class with an abstract method compare() in Java and now whenever you call this sort() method you can pass different implementation of compare() to sort in different way. 

This is like passing dynamic code, much like Lambda expression of today's. In fact, Lambda is a better and more readable form of Anonymous class, sort of like Syntactic sugar. In runtime, JVM translates Lambda into Anonymous class itself. 


18. Give some examples of nested class from JDK

There are many nested class in JDK but the most popular ones are Map.Entry and LinkedList.Node, both are two good examples of nested classes in Java.


19. What is the use of local inner class in Java?

You can use local inner class for ad-hoc purpose. The key advantage of local inner class is that you can use it access not only members of enclosing class's but also all the local variables which are defined in the same block. 


20. Does Inner classes are compiled into separate class file?

Yes, Inner class is compiled into separate files, you can compile a class with an Anonymous class and you can easily see them when you compile a class using Maven or just javac. You will see multiple *.class files with with names like EnclosingClass$n.class where EnclosingClass is the top level class where Anonymous class is declared or used. 


That's all about popular nested class and inner class questions for Java Interviews. You can use these questions to not just prepare for Java developer interview but also to learn nested static class and inner class better. It's one of those topics which separates a good Java developer from an average Java developer and mastering this will not only help Java Interviews but also enhance your reputation as competent Java developer. 


Other Programming and Technical Interview Questions you may like:


Thanks for reading this article so far. If you like these nested and static class interview questions and answers then please share with your friends and colleagues. If you have any questions or doubt feel free to ask in comments. 


No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.