Four Usages of Internal Classes

Links to the original text: https://my.oschina.net/u/2385466/blog/547059

Inner Class

Organizing related classes reduces namespace confusion.
An internal class can be defined in another class, in a function, or even as part of an expression.
There are four internal classes in Java:
static inner class (also called nested class)
member inner class
local inner class
anonymous inner class

Static Inner Class

The simplest form of internal class.
The static keyword is added to the class definition.
You cannot have the same name as an external class.
It is compiled into a completely independent. class file named OuterClass$InnerClass.class.
Only static members and methods of external classes can be accessed, including private static members and methods.
The way to generate static internal class objects is as follows:
OuterClass.InnerClass inner = new OuterClass.InnerClass();
Static internal classes use code:

package com.learnjava.innerclass;

class StaticInner
{
    privatestaticint a = 4;

    // Static inner class publicstaticclass Inner
    {
        publicvoid test()
        {
            // Static internal classes can access static members of external classes
            // And it can only access static
            System.out.println(a);
        }

    }
}

publicclass StaticInnerClassTest
{

    publicstaticvoid main(String[] args)
    {
        StaticInner.Inner inner = new StaticInner.Inner();
        inner.test();
    }
}

Member Inner Class

The member inner class is also defined in another class, but it is not modified by static.
Membership inner class and static inner class can be analogous to non-static member variable and static member variable.
The member inner class is like an instance variable.
It can access all member variables and methods of its external classes, whether static or non-static.
Create instances of member inner classes in external classes:
this.new Innerclass();
Create instances of internal classes outside of external classes:
(new Outerclass()).new Innerclass();
Access members of external classes in internal classes:
Outerclass.this.member
See code examples for details:

package com.learnjava.innerclass;

class MemberInner
{
    privateint d = 1;
    privateint a = 2;

    // Define a member inner class publicclass Inner2
    {
        privateint a = 8;

        publicvoid doSomething()
        {
            // Direct access to external class objects
            System.out.println(d);
            System.out.println(a);// Direct access to a, then access to a in the internal class

            // How do I access a in an external class?
            System.out.println(MemberInner.this.a);
        }

    }

}

publicclass MemberInnerClassTest
{

    publicstaticvoid main(String[] args)
    {

        // Objects that create member inner classes
        // You need to create an instance of an external class first
        MemberInner.Inner2 inner = new MemberInner().new Inner2();

        inner.doSomething();
    }
}

Local Inner Class

Local internal classes are defined in methods with a smaller scope than methods. It is the least used type in internal classes.
Like local variables, they cannot be modified by public, protected, private, and static.
Local variables of type final defined in the method can only be accessed.
Local internal classes are defined in methods, so they can only be used in methods, that is, they can only generate instances of local internal classes in methods and call their methods.

package com.learnjava.innerclass;

class LocalInner
{
    int a = 1;

    publicvoid doSomething()
    {
        int b = 2;
        finalint c = 3;
        // Define a local inner class class Inner3
        {
            publicvoid test()
            {
                System.out.println("Hello World");
                System.out.println(a);

                // Not accessible to non-final local variables
                // error: Cannot refer to a non-final variable b inside an inner
                // class defined in a different method
                // System.out.println(b);

                // You can access final variables
                System.out.println(c);
            }
        }

        // Create an instance of a local inner class and call the method new Inner3().test();
    }
}

publicclass LocalInnerClassTest
{
    publicstaticvoid main(String[] args)
    {
        // Create external class objects
        LocalInner inner = new LocalInner();
        // Calling methods of external classes
        inner.doSomething();
    }

}

Anonymous Inner Class

Anonymous inner classes are local inner classes without names. They do not use keywords class, extends, implements, and have no construction methods.
Anonymous inner classes implicitly inherit a parent class or implement an interface.
Anonymous inner classes are often used as a method parameter.

package com.learnjava.innerclass;

import java.util.Date;

publicclass AnonymouseInnerClass
{

    @SuppressWarnings("deprecation")
    public String getDate(Date date)
    {
        return date.toLocaleString();

    }

    publicstaticvoid main(String[] args)
    {
        AnonymouseInnerClass test = new AnonymouseInnerClass();

        // Print date:
        String str = test.getDate(new Date());
        System.out.println(str);
        System.out.println("----------------");

        // Using anonymous inner classes
        String str2 = test.getDate(new Date()
        {
        });// The curly brackets are used, but the contents are not filled in. The execution results are exactly the same as those above.
            // Generate an object that inherits a subclass of the Date class
        System.out.println(str2);
        System.out.println("----------------");

        // Use anonymous inner classes and override methods in parent classes
        String str3 = test.getDate(new Date()
        {

            // Override methods in parent classes
            @Override
            @Deprecated
            public String toLocaleString()
            {
                return "Hello: " + super.toLocaleString();
            }

        });

        System.out.println(str3);
    }
}

In the generated. class file, the anonymous class generates the OuterClass .class file, and the number is based on the number of anonymous classes.
Examples of using internal classes in Swing are as follows:

package com.learnjava.innerclass;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;

publicclass SwingTest
{
    publicstaticvoid main(String[] args)
    {
        JFrame frame = new JFrame("JFrame");
        JButton button = new JButton("JButton");

        button.addActionListener(new ActionListener()
        {
            // new comes out with an example of a class that implements the ActionListener interface

            @Override
            publicvoid actionPerformed(ActionEvent arg0)
            {
                System.out.println("Hello World");

            }
        });

        //add button
        frame.getContentPane().add(button);

        //Setting Close Behavior
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setSize(200, 200);

        frame.addWindowListener(new WindowAdapter()
        {
            //You can also use anonymous inner classes that inherit adapter classes
            @Override
            publicvoid windowClosing(WindowEvent e)
            {

                System.out.println("Closing");
                System.exit(0);
            }
        });
        frame.setVisible(true);
    }

}

Reproduced in: https://my.oschina.net/u/2385466/blog/547059

Tags: Java

Posted on Thu, 12 Sep 2019 23:11:40 -0700 by usefulphp