Regular Inner Classes

Recall that you can write many different classes in one source file. You can also write a class inside of another class.

Why in the world would you want to do that? Well, they sort of allow you to scope your classes. The inner class becomes a member of the outer class. That is, the inner class acts as a member of the outer class, just like its methods and fields.

Important thing: Objects in an inner class have access to even the private variables in instances of the outer class.

You typically use an inner class to define a helper—that is, a class with a very specific purpose. In GUI development, you need to create listeners that handle events such as mouse clicks. Often, these events are handled using inner classes.

There are four kinds of inner classes that are tailored for different purposes. The first is the easiest.

It is simple business, defining an inner class. Try something like this:

class MyOuterClass {
   class MyInnerClass {
   }
}

To instantiate an inner class, you must first have a reference to the outer class. In general, an object of an inner class is created by the outer class itself.

A class can define as many inner classes as it feels like putting up with.

An advantage to using inner classes is that they can be hidden from other classes in the same package, so you can restrict access to their functionality.

Inner classes can be declared private. This is different than regular classes, which must be default or public.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.19.75