Chris
Chris

Reputation: 6611

Why so many inner classes in Android?

I am a new fish in Android development. While reading books and Android source code I found out that there so many inner classes in the Android application. Why does Android need so many inner classes?

I am confused by these inner classes.

Upvotes: 7

Views: 2066

Answers (5)

erDave
erDave

Reputation: 31

Simply put, when translated into bytecode, inner classes are "rebuilt" as external classes in the same package. This means any class in the package can access this inner class. The owner/enclosing/father classes’ private fields are morphed into protected fields as they are accessible by the now external inner class.

OWASP Recommendation

So basically, it's just a "shortcut" that compromises the security of your own design.

So, there are not "needed" by Android in that sense.

Upvotes: 3

neteinstein
neteinstein

Reputation: 17613

This may also interest you:

Android: AsyncTask recommendations: private class or public class?

Its not about why, but which is preferred inner or outter classes for AsyncTasks, one of the most prone classes to be used as inner.

Upvotes: 0

Sam
Sam

Reputation: 2552

I am guessing you have been doing C/C++ before. These inner classes are not Android specific. They come from Java. In Java, stacks (which in C/C++ we live by) do not exist in the same manner. Think of Java byte code as a blob of binary executable that exist inside one function (kind of like writing all of your code inside the main function in C/C++). But Java allows you to be "Object Oriented" and localize your code in classes for diffrent tasks. It also allows you to derive from another class and instantiate it at the same time. That is what you see in all the examples. The link that "Macarse" has provided explains this for a Java programmer.

Upvotes: 2

Macarse
Macarse

Reputation: 93143

Inner classes are not just in Android. I guess you need to understand why they are good in some cases.

Check this article about Inner classes: Inner classes: So what are inner classes good for anyway?.

Upvotes: 5

Al Sutton
Al Sutton

Reputation: 3924

They are often the most efficient way of implementing a design.

An inner class can access the private members of the class which contains it, so using an inner class allows a split of functionality between classes without the need to add accessor methods for private variables.

Upvotes: 7

Related Questions