Enter your keyword

post

Inner Classes

Definition


Inner classes are a security mechanism in Java. We know a class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private. And this is also used to access the private members of a class.

Example

class Outer_Demo{
int num;
//inner class
private class Inner_Demo{
public void print(){
System.out.println("This is an inner class");
}
}
//Accessing he inner class from the method within
void display_Inner(){
Inner_Demo inner = new Inner_Demo();
inner.print();
}
}

public class My_class{
public static void main(String args[]){
//Instantiating the outer class
Outer_Demo outer = new Outer_Demo();
//Accessing the display_Inner() method.
outer.display_Inner();
}

}

Commonly asked interview questions on Constructors

1)What is an inner class?

Answer :Inner class is a class defined inside other class and act like a member of the enclosing class.

2) What is static member class?

Answer :A static member class behaves much like an ordinary top-level class, except that it can access the static members of the class that contains it. The static nested class can be accessed as the other static members of the enclosing class without having an instance of the outer class. The static class can contain non-static and static members and methods.

3) What are the different types of inner classes?

Answer : There are two main types of inner classes –

Static member class
Inner class
Member class
Anonymous class
Local class

4) What are non static inner classes?

Answer :The different type of static inner classes are: Non – static inner classes – classes associated with the object of the enclosing class.

Member class – Classes declared outside a function (hence a “member”) and not declared “static”.
The member class can be declared as public, private, protected, final and abstract. E.g.

public class InnerClass {
class MemberClass {
public void method1() { }
}
}

5)How to access the inner class from code within the outer class?

Answer :The inner class is instantiated only through the outer class instance.
class EnclosingOuter {
private int noInnerClass = 1;
public void getNoOfInnerClasses(){
Inner in = new Inner();
System.out.println(“No Of Inner classes is :”+ in.getNoOfClassesFromOuter());
}
class Inner{
public int getNoOfClassesFromOuter(){
return noInnerClass;
}
}
Here the method getNoOfInnerClasses() is called on the outer class’s instance through this outer class instance the inner class instance in is created.

Take Sample Test

Reference Books


1. Head First Java

No Comments

Add your review

Your email address will not be published.