Java Inner Class, a similar concept is also found in C++, that is, Nested Class. At first glance, internal classes may seem a bit redundant, and their usefulness may not be that significant for beginners, but with an in-depth understanding of it, you will find that Java designers are indeed well-intentioned in internal classes. Learning to use internal classes is part of mastering advanced Java programming, which allows you to design your program structure more elegantly. The following are introduced from the following aspects:
First meeting
public interface Contents { int value();}public interface Destination { String readLabel();}public class Goods { private class Content implements Contents { private int i = 11; public int value() { return i; } } protected class GDestination implements Destination { private String label; private GDestination(String whereTo) { label = whereTo; } public String readLabel() { return label; } } public Destination dest(String s) { return new GDestination(s); } public Contents content() { return new Content(); }}class TestGoods { public static void main(String[] args) { Goods p = new Goods(); Contents c = p.cont(); Destination d = p.dest("Beijing"); }}In this example, the classes Content and GDestination are defined inside the class Goods, and have protected and private modifiers respectively to control the access level. Content represents the content of Goods, while GDestination represents the destination of Goods. They implement two interfaces Content and Destination, respectively. In the main method below, use Contents c and Destination d directly to operate, and you don’t even see the names of these two internal classes! In this way, the first benefit of internal classes is reflected - hiding operations that you don't want others to know, that is, encapsulation.
At the same time, we also discovered the first method to obtain inner class objects outside the scope of the external class, that is, to use the methods of its external class to create and return. This is how the cont() and dest() methods in the above example do. So is there any other way? Of course, the syntax format is as follows:
outerObject=new outerClass(Constructor Parameters); outerClass.innerClass innerObject=outerObject.new InnerClass(Constructor Parameters);
Note that when creating non-static inner class objects, you must first create the corresponding outer class objects. As for the reason, it also leads to our next topic-
Non-static inner class objects have references to their outer class objects
A little modification to the example just now:
public class Goods { private valueRate=2; private class Content implements Contents { private int i = 11*valueRate; public int value() { return i; } } protected class GDestination implements Destination { private String label; private GDestination(String whereTo) { label = whereTo; } public String readLabel() { return label; } } public Destination dest(String s) { return new GDestination(s); } public Contents content() { return new Content(); }}The modified part is shown in red. Here we add a private member variable valueRate to the Goods class, which means the value coefficient of the goods. Multiply it when the internal class Content method value() calculates the value. We found that value() can access valueRate, which is also the second benefit of inner classes - an inner class object can access the content of the external class object that created it, even including private variables! This is a very useful feature that provides us with more ideas and shortcuts when designing. To implement this function, the inner class object must have a reference to the outer class object. When the Java compiler creates an internal class object, it implicitly passes the reference to its external class object and saves it all the time. This allows inner class objects to always access their external class objects, which is also why outside the scope of external class actions, the external class object must be created first.
Some people may ask, what if a member variable in an inner class is the same as a member variable in an outer class, that is, a member variable of the same name in the outer class is blocked? It's okay, Java uses the following format to express references to external classes:
outerClass.this
With it, we are not afraid of such blocking situations.
Static inner class
Like ordinary classes, inner classes can also be static. However, compared with non-static inner classes, the difference is that the static inner classes have no references to the outside. This is actually very similar to the nested classes in C++. The biggest difference between Java internal classes and C++ nested classes is whether there are references to the outside. Of course, there is a difference from the perspective of design and some details of it.
In addition, in any non-static inner class, there cannot be static data, static methods, or another static inner class (the inner class can be nested more than one layer). However, static inner classes can have all this. This is also the second difference between the two.
Local internal classes
Yes, Java internal classes can also be local, and they can be defined within a method or even a code block.
public class Goods1 { public Destination dest(String s) { class GDestination implements Destination { private String label; private GDestination(String whereTo) { label = whereTo; } public String readLabel() { return label; } } return new GDestination(s); } public static void main(String[] args) { Goods1 g= new Goods1(); Destination d = g.dest("Beijing"); }}This is an example above. In the method dest we define an inner class, and finally this method returns the object of this inner class. This can be done if we only need to create one of its objects and create it to the outside when using an inner class. Of course, internal classes defined in methods can diversify designs, and the purpose is not just in this sense.
Here is a more bizarre example:
public class Goods2{ private void internalTracking(boolean b) { if(b) { class TrackingSlip { private String id; TrackingSlip(String s) { id = s; } String getSlip() { return id; } } TrackingSlip ts = new TrackingSlip("slip"); String s = ts.getSlip(); } } public void track() { internalTracking(true); } public static void main(String[] args) { Goods2 g= new Goods2(); g.track(); }}You can't create an object of this inner class outside of if, because this is beyond its scope. However, when compiling, the inner class TrackingSlip is compiled at the same time as other classes, but it is invalid if it exceeds this scope due to its own scope. Apart from this, it is no different from other inner classes.
Anonymous internal class
The syntax rules of java's anonymous internal classes look a bit weird, but like anonymous arrays, when you only need to create an object of a class and cannot use its name, using an internal class can make the code look concise and clear. Its syntax rules are as follows:
new interfacename(){......}; or new superclassname(){......};Let’s continue to give an example:
public class Goods3 { public Contents content(){ return new Contents(){ private int i = 11; public int value() { return i; } }; }}Here, the method cont() uses an anonymous inner class to directly return an object that implements the class of the interface Contents, which looks very concise.
In the anonymous adapter for event processing in Java, anonymous inner classes are widely used. For example, when you want to close the window, add this code:
frame.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); }});One thing to note is that since the anonymous inner class has no name, it does not have a constructor (but if this anonymous inner class inherits a parent class that only contains a constructor with arguments, you must bring these parameters when creating it, and use the super keyword to call the corresponding content during the implementation process). If you want to initialize its member variables, there are several ways:
If it is an anonymous inner class of a method, you can use this method to pass the parameters you want, but remember that these parameters must be declared final.
Reform anonymous inner class into a named local inner class so that it can have a constructor.
Use initialization code blocks in this anonymous inner class.
Why do internal classes need?
What are the benefits of java internal classes? Why do internal classes need?
First, let’s give a simple example. If you want to implement an interface, but one method in this interface has the same name and parameters as one method in the class you imagined, what should you do? At this time, you can create an internal class to implement this interface. Since the inner class is accessible to all contents of the outer class, doing so can accomplish all the functions you directly implement this interface.
But you may have to question, isn’t it enough to change the method?
Indeed, it is really unconvincing to use this as a reason to design internal categories.
The real reason is that the internal classes and interfaces in java are combined to solve a problem that is often complained about by C++ programmers - there is no more inheritance. In fact, multi-inheritance of C++ is very complicated to design, and Java can achieve the effect of multi-inheritance through internal classes and interfaces.
Java internal class summary
(1) Non-static inner class defined between methods:
● Peripheral and internal classes can access their own private members from each other.
● Static member variables cannot be defined in the inner class.
Out of the scope of the external class, to create an internal class object, you must first create its external class object
(2) Static inner class defined between methods:
● Only static members of external classes can be accessed.
Static inner class has no references to the outside
(3) Local inner class defined in the method:
● This internal class does not have any access control permissions
● The peripheral class cannot see the local inner class in the method, but the local inner class can access any member of the peripheral class.
● Local internal classes can be accessed in the method body, but the access statement must be after defining the local internal classes.
● Local internal classes can only access constants in the method body, that is, members modified with final.
(4) Anonymous inner class defined in the method:
● There is no constructor, instead passing the constructor parameters to the superclass constructor
When you only need to create an object of a class and don't use its name, using anonymous inner classes can make the code look concise and clear.
The above article comprehensively understands internal and anonymous classes in Java is all the content I have shared with you. I hope it can give you a reference and I hope you can support Wulin.com more.