What are inner classes?

Java inner class

In contrast to so-called top-level classes , which are defined as an independent compilation unit directly in their own *.javafiles, inner classes are those that lie within the code block of another, enclosing class.

Basically, classes and interfaces can be nested in one another in Java. The structure of the source text is basically as follows:

// File: OuterClass.java class OuterClass { // … class InnerClass { // … } // … }

The outer class is the one that *.javagives the file its name, in this case OuterClass.java.

The use of inner classes does not serve to expand the linguistic possibilities. Rather, it is suitable for optimizing program design by creating a close relationship between the included and the enclosing class.

There are four different types of inner classes. They differ in terms of their visibility, access and use options. The compiler *.classsaves them in separate files. They have identifiers in which the name of the outer $class is followed by that of the inner class , separated by a dollar sign ( ). The only exception is the naming of anonymous inner classes , which are numbered consecutively in the absence of an identifier.

Nested top-level classes

This statictype, which is always declared, is immediately available in other classes without creating an object in the surrounding class. Its definition can also be in another inner top-level class. There are no limits to the nesting depth. 
The designation of this type also shows that the behavior and handling differ only slightly from ‘normal’ top-level classes. In particular, objects can be created without a reference to the outer class.

package test; public class OuterClass { static String s1 = “Variable static OuterClass.s1 called”; String s2 = “Variable OuterClass.s2 called”; public static class InnerClass { public void print () { System.out.println (“InnerClass # print () called”); System.out.println (s1); System.out.println (s2); // Error } } }

If a nested inner class is addressed, the package name and the name of the surrounding class must precede the identifier of the inner class, connected by the dot operator. A corresponding importinstruction is of course also permitted.

import test.OuterClass; public class test { public static void main (String [] args) { OuterClass.InnerClass ai = new OuterClass.InnerClass (); // alternatively with omission of the import statement // test.OuterClass.InnerClass ai = new test.OuterClass.InnerClass (); ai.print (); } }

For access to variables of the outer class from the inner class, these must be static declared, since they are addressed from a static environment. 
Conversely, if you want to access variables of the inner class in the outer class, the usual rules apply: Access can either take place via an object of the inner class, or, staticif the variables are declared, with a preceding class identifier without creating an object. 
As mentioned above, the compiler provides the *.classfiles of nested top-level classes with an identifier during compilation, which consists of the name of the outer class and that of the inner class, separated by an ‘ $’.

Element classes

Element classes are ‘real’ classes that static are defined in the code block of another class and can be nested at any depth, which are not declared and which must not contain any only staticdeclared elements. However, constants, variables declared as static and final, are allowed. Element classes 
have access to all, including privateor staticdeclared, elements of the surrounding class.

public class OuterClass { private String s1 = “Variable OuterClass.s1 called”; static String s2 = “Variable OuterClass.s2 called”; public class InnerClass { static final String s3 = “static and final”; // allowed static String s4 = “only static”; // Error public void print () { System.out.println (s1); System.out.println (s2); } } }

Element classes do not exist independently of their surrounding class. Each of its objects is assigned to one of the outer class. The *.classfile also consists of the name of the outer class and that of the inner separated by a ‘ $’. 
When creating an object for an element class, you should pay attention to the somewhat unusual notation in which the object of the outer class is connected to the constructor call by newthe inner class using the dot operator .

OuterClass oc = new OuterClass (); OuterClass.InnerClass ic = oc.new InnerClass (); // returns oc $ ic.class

If there are elements with the same identifier in the outer and inner class, those of the outer class are covered in the inner class. In order to still be able to access the elements of the outer class in such cases, the keyword is used this in combination with the outer class name:

public class OuterClass { private String s1 = “Variable OuterClass.s1 called”; public class InnerClass { private String s1 = “Variable InnerClass.s1 called”; public void print () { System.out.println (OuterClass.this.s1); // Variable OuterClass.s1 called } } }

Local classes

Local classes are those that are defined in the statement blocks of methods, constructors, etc. of an outer class. Local interfaces are not possible. Access modifiers are also not permitted in the class declaration. Class methods and static variables are allowed in local classes does not exist, staticand finaldeclared constants, however, very well.

public class OuterClass { String s1 = “Variable OuterClass.s1 called”; public void print () { String s2 = “Variable s2 called in OuterClass.print ()”; class InnerClass { String s3 = “Variable InnerClass.s3 called”; InnerClass () { System.out.println (s1); // Variable OuterClass.s1 called System.out.println (s2); // Variable s2 in OuterClass.print () called System.out.println (s3); // Variable InnerClass.s3 called } } new InnerClass (); System.out.println (s3); // Error } public static void main (String [] args) { new OuterClass (). print (); } }

Local inner classes have direct access to the variables of the outer class, but vice versa, access to the variables of the inner class is only possible with one of the objects.

Anonymous inner classes

Anonymous classes are inner classes from which an object is always formed, but which do not have their own identifier. For this reason, the compiler also *.classstores them in consecutively numbered files, with the name of the outer class, separated by a dollar sign, followed by the serial number of the inner anonymous classes contained in the class. This also applies to heavier nesting. So three are in the example below, the compiler *.classfiles created: AnonClass.class,AnonClass$1.class, and AnonClass$1$1.class.

Inner anonymous classes behave like local classes. In addition, they must not contain extends- or – implementsspecifications and no constructor. They either extend an existing class or they inherit from Objectand implement an interface. The latter variant is often found in event handling.

import java.awt.BorderLayout; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; public class AnonClass extends JFrame { public AnonClass () { JButton butt = new JButton (“click”); butt.addActionListener (new ActionListener () { public void actionPerformed (ActionEvent e) { System.out.println (new Rectangle (40, 20) { public string toString () { return “mass of the rectangle” + getWidth () + “x” + getHeight (); }; }); } }); this.add (butt, BorderLayout.CENTER); this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); this.setTitle (“Anon. Class Example”); this.setSize (200, 200); this.setLocationRelativeTo (null); this.setVisible (true); } public static void main (String [] args) { new AnonClass (); } }

The example demonstrates both variants. An anonymous class is passed to the method addActionListener()as a parameter. You can see here that newthe interface is ActionListeneraddressed after and its method is actionPerformed() implemented in the subsequent block . 
A console output is also System.out.println()generated in the code block of the method . The method println()is in turn passed an anonymous Rectangleclass derived from as a parameter in which it is toString()overwritten.

The Stringrepresentation of the automatically generated object is output Rectangle, which in turn is executed by clicking the button and the associated event handling.

مقالات ذات صلة:

اترك تعليقاً

لن يتم نشر عنوان بريدك الإلكتروني. الحقول الإلزامية مشار إليها بـ *