Wednesday, November 2, 2011

Inner class Interview Question Answer


Question: What are different types of inner classes ?
Answer: Inner classes nest within other classes. A normal class is a direct member of a package. Inner classes, which became available with Java 1.1, are four types
·       Static member classes
·       Member classes
·       Local classes
·       Anonymous classes

Static member classes - a static member class is a static member of a class. Like any other static method, a static member class has access to all static methods of the parent, or top-level, class.

Member Classes - a member class is also defined as a member of a class. Unlike the static variety, the member class is instance specific and has access to any and all methods and members, even the parent's this reference.

Local Classes - Local Classes declared within a block of code and these classes are visible only within the block.

Anonymous Classes - These type of classes does not have any name and its like a local class

Question: What is an inner class
Answer: An inner class is same as any other class, but is declared inside some other class

Question: How will you reference the inner class
Answer: To reference it you will have to use OuterClass$InnerClass

Question: Can objects that are instances of inner class access the members of the outer class
Answer: Yes they can access the members of the outer class

Question: What modifiers may be used with an inner class that is a member of an outer class?
Answer: A (non-local) inner class may be declared as public, protected, private, static, final, or abstract

Question: Can inner classes be static
Answer: Yes inner classes can be static, but they cannot access the non static data of the outer classes, though they can access the static data.

Question: Can an inner class be defined inside a method
Answer: Yes it can be defined inside a method and it can access data of the enclosing methods or a formal parameter if it is final

No comments:

Post a Comment