Monday, December 4, 2017

Interview Question -inner classes

Can we declare a class as static?

We can’t declare a top-level class as static however an inner class can be declared as static. If inner class is declared as static, it’s called static nested class.
The static nested class is the same as any other top-level class and is nested for only packaging convenience.

  1. What is inner class in java?

    We can define a class inside a class and they are called nested classes. Any non-static nested class is known as inner class. Inner classes are associated with the object of the class and they can access all the variables and methods of the outer class. Since inner classes are associated with the instance, we can’t have any static variables in them.
    We can have local inner class or anonymous inner class inside a class. For more details read java inner class.
  2. What is anonymous inner class?

    A local inner class without name is known as anonymous inner class. An anonymous class is defined and instantiated in a single statement. Anonymous inner class always extend a class or implement an interface.
    Since an anonymous class has no name, it is not possible to define a constructor for an anonymous class. Anonymous inner classes are accessible only at the point where it is defined.

No comments:

Post a Comment