Top 19 Java Inner Classes Interview Questions
Q1. What Is Static Member Class?
A static member elegance behaves much like an ordinary top-level class, besides that it is able to access the static contributors of the beauty that includes it. The static nested class can be accessed as the other static individuals of the enclosing class whilst no longer having an example of the outer magnificence. The static beauty can include non-static and static members and strategies.
Public magnificence InnerClass
static elegance StaticInner
static int i = nine;
int no = 6;
personal void method()
public void method1()
static void method2()
very last void method3()
The static internal elegance may be accessed from Outer Class in the following manner:
InnerClass.StaticInner staticObj= new InnerClass. StaticInner ();
No outer magnificence example is required to instantiate the nested static elegance because of the fact the static magnificence is a static member of the enclosing elegance.
Q2. What Is An Inner Class?
Inner magnificence is a category defined interior every different beauty and act like a member of the enclosing magnificence.
Q3. What Are Disadvantages Of Using Inner Classes?
Using internal class increases the whole kind of lessons being used by the software. For all of the instructions created via JVM and loaded inside the memory, jvm has to perform a few duties like developing the object of type magnificence. Jvm may should perform some ordinary responsibilities for those extra classes created which can also stop end result slower performance if the software program is using greater extensive type of inner instructions.
Inner classes get restricted resource of ide/gear in contrast to the top level training, so working with the internal training is from time to time traumatic for the developer.
Q4. Can An Anonymous Class Define Method Of Its Own?
Yes. But there may be no way via which the techniques described in the anonymous elegance which are not present in its superclass be invoked. As most effective the ones strategies which can be described in the superclass which the nameless magnificence extends be invoked. Hence defining the techniques within the nameless beauty can be of little want.
Q5. Can The Method Local Inner Class Object Access Method Local Variables?
No, a way neighborhood inner magnificence object can not get admission to the technique nearby variable.
Reason: The local variables are not guaranteed to stay so long as the nearby internal magnificence devices. The method community variable live on stack and exist great until the method lives, their scope is restrained upto the code inside the technique they will be declared in. But the community internal class item created in the approach lives on heap and it could exist even after the technique ends if in case the reference of this close by internal elegance is exceeded into some other code and is stored in an example variable. So we can't make certain that the local variables will stay till the technique nearby internal elegance object lives, therefore the technique close by inner beauty object cannot get right of entry to the technique local variable. To access the approach local variables, the variable ought to be declared as final.
Q6. Can A Method Local Inner Class Access The Local Final Variables? Why?
Yes. Because the final variables are stored on heap and stay as long as the approach close by inner class objects might also stay.
Q7. Which Modifiers Can Be Applied To The Inner Class?
Following modifiers can be carried out to the inner elegance:
Public
Private
Abstract
Final
covered
Strict
Static – turns the internal class into
Static nested elegance
Q8. If You Compile A File Containing Inner Class How Many .Elegance Files Are Created And Are All Of Them Accessible In Usual Way?
If a internal elegance enclosed with an outer class is compiled then one .Elegance file for every inner magnificence and a .Magnificence report for the outer beauty is created.
Example:
class EnclosingOuter
beauty Inner
If you bring together the above code with command:
% javac EnclosingOuter.Java Two documents may be created. Though a separate inner class document is generated, the inner elegance record is not on hand inside the common manner.
EnclosingOuter.Class
EnclosingOuter$Inner.Class
Q9. What Are The Different Types Of Inner Classes?
The under mentioned are the types of inner instructions:–
Static member magnificence
Inner elegance
Member magnificence
Anonymous elegance
Local elegance
Q10. How To Access The Inner Class From Code Within The Outer Class?
The inner class is instantiated best thru the outer elegance instance.
Class EnclosingOuter
personal int noInnerClass = 1;
public void getNoOfInnerClasses()
Inner in = new Inner();
System.Out.Println("No Of Inner classes is :"+ in.GetNoOfClassesFromOuter());
magnificence Inner
public int getNoOfClassesFromOuter()
move returned noInnerClass;
Here the method getNoOfInnerClasses () is known as on the outer elegance’s instance and through this outer elegance instance the inner magnificence example is created.
Q11. Can A Local Class Declared Inside A Static Method Have Access To The Instance Members Of The Outer Class?
No. There is not any reference available in the static approach about the instance members of the outer magnificence. The static technique elegance can not have get admission to to any contributors of the outer elegance aside from static members.
Q12. What Are Non Static Inner Classes?
The exceptional sort of static internal commands is: Non - static inner classes – classes associated with the item of the enclosing class.
Member class - Classes declared outside a function (as a result a "member") and no longer declared "static". The member class can be declared as public, private, included, very last and precis.
Example:
public class InnerClass
elegance MemberClass
public void method1()
Method nearby magnificence – The inner elegance declared inside the approach is referred to as technique neighborhood internal magnificence. Method neighborhood inner beauty can only be declared as very last or abstract. Method nearby elegance can simplest get entry to global variables or technique close by variables if declared as final
public class InnerClass
int i = 9;
public void method1()
final int ok = 6;
magnificence MethodLocal
MethodLocal()
System.Out.Println(okay + i);
Anonymous internal magnificence - These are community instructions which are automatically declared and instantiated within the center of an expression. Also, like community instructions, nameless training cannot be public, private, covered, or static. They can specify arguments to the constructor of the superclass, however can't otherwise have a constructor. They can implement most effective one interface or enlarge a class.
Public elegance MyFrame extends JFrame
JButton btn = new JButton();
MyFrame()
btn.AddActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
);
//Anonymous class used with comparator
List l = new ArrayList();
l.Upload(new Parent(2));
l.Upload(new Parent(3));
Collections.Sort(l, new Comparator()
public int examine(Object o1, Object o2)
Parent prt1 = (Parent) o1;
Parent prt2 = (Parent) o2;
if (prt1.GetAge() > prt2.GetAge())
go back -1;
else if(prt1.GetAge()
return 1;
else
pass again zero;
);
Q13. Which Modifiers Can Be Applied To The Method Local Inner Class?
Only summary or very last key-word is allowed.
Q14. Can An Anonymous Class Implement An Interface And Also Extend A Class At The Same Time?
No. An anonymous beauty can both expand a category or put into impact a single interface. If the anonymous elegance is extending a category then it routinely turns into the implementer of all the interfaces applied thru its superclass.
Q15. What Are The Advantages Of Inner Classes?
The embedding of internal class into the outer elegance inside the case when the internal class is for use simplest by using using one magnificence i.E. The outer class makes the package deal more streamlined. Nesting the internal class code where it's miles used (inside the outer class) makes the code greater readable and maintainable. The internal class stocks a special relationship with the outer class i.E.
The internal class has access to all individuals of the outer class and still have its private kind is the precept benefits of Inner elegance. Advantage of inner class is that they can be hidden from the opposite training in the equal package deal and also have the get proper of entry to to all the participants (non-public additionally) of the enclosing elegance. So the outer class contributors which is probably going to be utilized by the inner class can be made non-public and the inner magnificence members may be hidden from the training inside the same bundle.
This will increase the extent of encapsulation. If a category A is written calls for some different magnificence B for its own use, there are methods to try this. One manner is to jot down down a separate magnificence B or to write down down an inner magnificence B interior beauty A. Advantage of writing the internal class B within the class A is you may avoid having a separate class. Inner commands are fine used in the event managing mechanism and to put into effect the helper training. The gain of the usage of internal elegance for occasion handling mechanism is that the use of if/else to pick the thing to be dealt with can be avoided. If internal instructions are used every thing receives its very own event handler and each event handler implicitly knows the issue it is operating for.
Q16. What Are Different Types Of Anonymous Classes?
Plain vintage nameless elegance type one:–
class superclass
void doSomething()
System.Out.Println(“Doing a few aspect within the Super magnificence”);
elegance hasAnonymous
superClass anon = new superClass()
void doSomething()
System.Out.Println(“Doing some thing within the Anonymous beauty”);
;
Here anon is the reference that's of kind superclass it really is the class extended with the aid of the anonymous class i.E. Superclass of the anonymous elegance. The method doSomething () is the exquisite elegance approach overridden via the nameless class.
Plain vintage anonymous elegance kind :–
interface Eatable
public void prepare Sweets();
elegance serveMeal
Eatable food = new Eatable()
public void
prepareSweets() //come implementation code goes right here
;
food is reference variable of kind Eatable interface which refers back to the nameless elegance that is the implementer of the interface Eatable. The nameless implementer elegance of the interface Eatable implements its approach prepare Sweets () internal it.
Argument described nameless beauty:–
interface Vehicle
void getNoOfWheels();
magnificence Car
void getType(Vehical v)
elegance BeautifulCars
void getTheBeautifilCar()
Car c = new Car ();
c.GetType (new Vehicle ()
public void getNoOfWheels ()
System.Out.Println("It has 4 wheels");
);
Anonymous magnificence is described due to the fact the argument of the method getTheBeautifilCar (), this anonymous class is the implementer of the interface Vehicle. The technique of sophistication Car getTheBeautifilCar () expects the argument as an object of type Vehicle. So first we create an item of Car referenced with the useful resource of the variable ‘c’. On this item of Car we name the technique getTheBeautifilCar () and in the argument we create an nameless class in region it truly is the implementer of interface Vehicle eventually of type Vehicle.
Q17. How To Create An Inner Class Instance From Outside The Outer Class Instance Code?
To create an instance of the internal beauty you ought to have the example of its enclosing elegance.
Magnificence Enclosing Outer
beauty Inner
To create the example of internal beauty from magnificence apart from the enclosing elegance.
1) elegance OtherThanOuter
Enclosing Outer out = new Enclosing Outer ();
EnclosingOuter.Inner in = out.New Inner ();
2) magnificence OtherThanOuter
EnclosingOuter.Inner out = new EnclosingOuter.Inner ();
Q18. Can A Method Which Is Not In The Definition Of The Superclass Of An Anonymous Class Be Invoked On That Anonymous Class Reference?
No. As the reference variable shape of the anonymous magnificence will be of superclass in order to no longer understand about any technique defined in the anonymous magnificence and as a result the compilation will fail.
Magnificence Superclass
void doSomething()
System.Out.Println ("In the Super elegance");
magnificence has Anonymous
Superclass anon = new Superclass ()
void doSomething()
System.Out.Println("In the Anonymous magnificence");
void doStuff()
System.Out.Println ("An Anonymous magnificence technique no longer discovered in
superclass");
;
public void doIt()
anon. DoSomething(); // prison superclass has this technique
anon. DoStuff(); // Not crook
The above code will not carry collectively because the superclass does now not recognise approximately the nameless elegance technique doStuff ().
Q19. Can A Static Nested Class Have Access To The Enclosing Class's Non-static Methods Or Instance Variables?
No.

