ADITYA VALLURU
ADITYA VALLURU

Reputation: 111

Difference between Inner Class methods VS Instance Methods in Java

What is the exact purpose of inner classes in Java and creating methods in it. Can I get the same behavior if I create methods in a class instead of creating those methods inside Inner class?

We can access both Inner class methods as well as instance methods outside of outer class. So what is the exact purpose of Inner classes in Java? Is there any situation/possibility where we can't survive without inner classes?

Upvotes: 2

Views: 924

Answers (3)

Lucas
Lucas

Reputation: 3281

Using them greatly depends on what you need to do. Sometimes you need a class that will be only used inside of one particular class, sometimes you need to quickly create an instance of Comparator and pass it to sort() method (anonymous inner class). Some inner classes are accessible outside of the class, some aren't. There are four different varieties of nested classes in java, for more I recommend reading this: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Upvotes: 2

Nikhil
Nikhil

Reputation: 310

you can refer to this

basically inner class keep the object oriented programming more intact. Also sometime when you have to implement an interface which has only one unimplemented method inner class comes handy. specially anonymous inner class. also instead of writing complicated if-else structure or switch case we can use this inner classes for callbacks

Upvotes: 0

Arijoon
Arijoon

Reputation: 2310

Inner class does not instantiate upon outer class instantiation unless you explicitly do it in the constructor. Therefore it's methods are not useful to the rest of the class unless they are static or you have created an instance of it and using them.

If you place your methods inside the inner class they can access the inner method, instance variables! You cannot access those variables in the outer class.

Upvotes: 0

Related Questions