Core Java Interview Questions-Inner classes

This Core Java Interview Questions-Inner classes page provides all the interview questions about java inner classes including the definition of inner classes, advantages of inner classes, static inner classes, non-static inner classes, local inner classes and anonymous inner classes.


What is Inner class?
Defining a class inside another class.
It is also called Nested class.


What are the advantages of Inner class?
Setting dependencies on Objects to access functionality.
Avoid collisions between class names.


How to instantiate non-static inner class?
Using Outer class Object instance.
OuterClass obj1 = new OuterClass();
OuterClass.InnerClass obj2 = obj1.new InnerClass();


How to access non-static members of the static inner class?
We can access static members of the static inner class directly as follows.
OuterClass.InnerClass.<static member> ;


Can an inner class be final?
Yes allowed.


What is a Local inner class?
Defining a class inside a method or block or constructor is called Local inner class.


What is Anonymous inner class?
Defining a class with no identity is called anonymous inner class.
It must be defined inside a method. Hence it is one type of local inner class.


Can we access private members of an Inner class from Outer class?
Yes.
It is not possible even in Parent-child relation also.


Can we apply access modifiers to Local inner class?
No, the local inner class scope belongs to block or method in which it has defined. Hence we cannot
apply access modifiers.


Can we define a Local inner class as static?
No, like local variables, we cannot declare local inner classes as static.


Where to access Local inner class?
Only with in the block or method in which it has defined.


Can we define constructors inside an Anonymous inner class?
No, because the anonymous inner class doesn’t have an identity.


What are the advantages of anonymous inner class?
Used to implement an interface with its original identity.


Write one advantage of Local inner class?
Avoid collisions between class names. Using local inner classes, we can define 2 classes with the same identity.


Can we pass interface instance as an argument?
Yes, we can directly pass interface instance as a parameter using anonymous inner class.


How to implement Runnable interface as Anonymous class ?
new Thread(new Runnable(){
public void run(){
logic
});


>Core Java Interview Questions-Serialization and Deserialization<

Share this