Inner Classes Flashcards

1
Q

What is a Nested Class?

A

In Java, a Nested class is a class declared inside another class. We can have more than one class declared inside a file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How many types of Nested classes

are in Java?

A
Member inner class
Local inner class
Anonymous inner class
Static nested class
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Why do we use Nested Classes?

A
Logical Grouping: We can logically group classes in one
place. If one class is useful to only one other class, then
we put smaller class within the larger class and keep them
in one file. This kind of nesting "helper classes" in a top level class makes the package more streamlined.
Encapsulation: Nested classes increase encapsulation. Let say there are two top-level classes, Foo and Bar. Bar
needs access to private members of Foo. We can hide class Bar within class Foo. In this way, private members of Foo can be accessed by class Bar. So class Foo remains
encapsulated. Also, class Bar remains hidden from the outside world.

Code Clarity: Nested classed make the code more readable and well organized. Only Top-level classes are exposed. The helper classes are kept hidden and closer the code where it is used by a Top-level class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the difference between a Nested class and an Inner class in Java?

A

An Inner class in Java is non-static class. It is a type of Nested class that is defined in another class but not qualified with a Static modifier. A Nested class is also a class can be Static Nested class or a non-Static Inner class.

An Inner class has access to other members of the enclosing class, even if they are declared private. A Static Nested class can not
access the other members of the enclosing class.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a Nested interface?

A

A Nested interface is declared inside another interface or a top level class. By default it is static.
A Nested interface is also known as Static interface.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Can an Interface be defined in a Class?

A

Yes, we can define a Static Nested interface within a class. Only the enclosing class can access it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

9.Do we have to explicitly mark a

Nested Interface public static?

A

A Nested Interface is implicitly public static. So the modifiers public and static are redundant in declaration.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Why do we use Static Nested interface in Java?

A

So the purpose of declaring an Inner interface is to restrict its access from outside world.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly