In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
How to understand the inner classes in Java programming? in view of this problem, this article introduces the corresponding analysis and solutions in detail, hoping to help more partners who want to solve this problem to find a more simple and easy way.
Inner class: a class defined within other classes, different from a combination. Although it looks like some kind of code-behind mechanism, it can be more versatile-you can understand the class that contains it and exchange data with it, and the code of the inner class can be more elegant and clear.
Inner class definition: included in other classes. There is not much difference between using and non-inner classes.
Typical usage: outer class returns a reference to inner class through a method.
One of the differences: the inner class name is nested within the outer class (outer class), and the inner class object is defined in the form of OuterClassName.InnerClassName outside the non-static method of Out class.
Note that non-static inner classes can only generate objects in the non-static method of Out class; in other classes, you must also use external class object instances of Out class. This ensures the link problem described below.
The second difference: inner classes can be private and protected.
Is Inner Class just a way to hide names (name-hiding) and organize code? NO .
The inner class object has a link (link to the enclosing object that made it) to the external class object from which it was created, so you can access the members of the external class object directly and without any restrictions, and the inner class can access all members of outer class (including private) (C++ 's nested classes do not have this feature); while outer class accesses members of inner class, you must create an object of Inner class and can access any member (including private).
The inner class object implicitly contains a reference to an external class object. Inner class object construction requires a reference to the outer class object, if not, compilation error (non-static inner class).
.this and .new: the former is used to return Outer class references, the correct type can be known and checked at compile time, and there is no runtime overhead; the latter is used to create an object of its inner class by the outer class object, OutClassObject.new InnerClassName () (note that outClassObj.new OutClassName.InnerClassName () cannot be used).
Nested class: static inner class, whose object creation does not require an outer class object reference, but can also be created in the static method.
Inner class and upcasting
The class implements the interface (interface), and other methods can take the interface as a parameter, not necessarily with the class (including class object definition) (similar to inheritance). You can use upcasting- > interface.
The upcasting inner class-> base class or interface (especially the latter) gives the inner class the opportunity to display its talents. The inner class of the implementation interface can be completely invisible and unavailable (via private or protected), and all you get is a reference to the base class or interface (through private, you cannot downcasting,protected, within the same package, or the inherited class can downcasting), making it easy to hide the implementation details.
The interface member is automatically public
Private inner classes can prevent any type-dependent code from hiding all implementation details. Also, there is no point in extending the interface because there is no access to methods outside the pubic interface, which allows JAVA to produce more efficient code.
Inner class can be defined in any scope (such as within a method).
Two reasons: 1. Implement an interface
two。 A private class is needed to help solve complex problems
Inner class form
1. The inner class in the method; 2. The inner class in a scope of the method; 3. Anonymous inner class that implements the interface; 4. Inherited anonymous inner class (the base class contains the constructor of parameters); 4. Anonymous inner class for member initialization; 5. An anonymous inner class constructed using an instance initialization block (anonymous classes do not have a constructor).
Local inner class (local inner class): an inner class defined within a method or in a scope of a method. Just because a local inner class is not visible outside the domain does not mean that its objects are not available. An inner class defined in a condition field does not mean that it is created by a condition.
Anonymous inner class (anonymous inner class): new T () {...}; {...} is the definition of anonymous inner class, ";" indispensable (; is just the end of the statement, not used to represent the end of anonymous inner class, so there is nothing special), create an object inherited from T's anonymous class, and the resulting reference can be automatically upcast to T. Is an abbreviation for the inner class defined earlier, except that the class does not have a name.
The previous case is when the base class constructor is the default constructor, when the base class constructor has parameters: new T (args) {...}; the corresponding base class constructor is called.
Anonymous inner class initialization: when you need to use an object of an externally defined class, the reference parameter passed must be final, otherwise an error will be reported in the compiler; an anonymous class cannot have a named constructor (of course, the class itself does not have a name). You can complete the constructor function through instance initialization (instance initialization). Because instance initialization cannot be overloaded (it does not mean there can be only one Instance initialization clause), anonymous inner classes can only have one constructor.
Anonymous inner classes can only choose between the inherited class and the implementation interface, and can only implement one interface.
Prefer classes to interfaces. Would you rather choose a class than an interface? )
Nested nested class: static inner class. It's a bit like the concept of C++ nested classes, but Java's nested classes have access to all members of outer class (including private, although of course only non-static members can be accessed through external class objects).
1. You do not need to create nested class objects through outer class objects (.new is not available?)
two。 Non-static outer class objects cannot be accessed through nested class objects (meaning direct access as if they were not nested classes)
3. The nested class object does not contain an outer class object reference (.this is not available).
4. Non-nested inner classes cannot have static members, methods, and nested classes (fields, methods levels must be consistent with class itself, non-static cannot contain static,non-static, and static can contain non-static).
Nested classes can be located inside the interface and do not violate the rules of the interface (cannot define interface instances? Only means that the nested class is placed under the namespace of the interface, and the class inside the interface is automatically public static (public nested class), and the nested class itself can implement the interface. The advantage is that the code used in all implementations of the interface can be written within the nested class.
Another use of nested classes: writing test code. Write main functions for each class to increase the length of the code, you can put main in the nested class, you can test the class to run the nested class; and in the release time, simply delete the .class file of the nested class before packaging.
Multiple nested classes (non-static and static) can have unrestricted access to all objects of any outer class.
Why use inner classes?
You don't always deal directly with the interface, sometimes you need to use the implementation of the interface. (you can implement multiple interfaces, but you cannot inherit multiple classes)
Reason: each inner class can inherit from one implementation independently, regardless of whether outer class already inherits another implementation. In effect, inner class provides the ability to multiple-inheritance (inherit from multiple classes) and provides another way to implement multiple interfaces (which seems less important than multiple inheritance, because multiple inheritance can only be implemented through internal classes).
Additional features:
1. An inner class can have multiple instances, and each instance can have different information independent of the outer class object
two。 An outer class can have multiple inner classes, and each inner class can implement the same interface or inherit the same class in a different way (see exercise 22, two inner classes implement the same interface in different ways, and only inner classes can do this)
3. The creation time of internal class instances is not limited by the creation of external class objects.
4. Using inner classes does not create confusion in "is-a" relationships, and each inner class is an entity.
Closures (closure) and callbacks (callback)
A closure is a callable object that records some information from the scope in which it was created.
An inner class is an object-oriented closure that not only contains information about the external class, but also manipulates all members, including private, by including a reference to the object of the external class.
Callback, through the information carried by other objects, the initial object can be called at a later time.
Java does not support pointer types and cannot implement callbacks through pointers. But the closures provided by inner classes are a better solution, more flexible and more secure (see example callbacks).
Private class Closure implements Incrementable {public void increment () {/ / Specify outer-class method, otherwise / / you'd get an infinite recursion: Callee2.this.increment ();}}
The value of callbacks lies in the flexibility to decide which methods to call at run time. GUI programming will be more obvious.
Internal Class and Control Framework (control frameworks)
An application framework (application framework) is a collection of classes or classes used to solve a particular type of problem. A typical application is to inherit one or more of these classes and override some methods. The code that rewrites the method specializes the general solution to solve specific problems. For example, template function mode. Design patterns separate the constant from the changing.
The control framework is a special kind of application framework used to respond to events. Systems that are mainly used to respond to events are called event-driven systems (event-driven system), such as GUI.
Inner classes make it easy to create and use control frameworks. The control framework itself does not include specific information about the things to be controlled. This information is provided during inheritance when implemented by the action () part of the algorithm. The things that change in the control framework are different action of various event objects, which is achieved by creating different event inheritance classes. (example event)
Control events use abstract classes instead of interfaces?
Inner classes play two roles in the control framework:
1. Used to represent the various action () needed to solve the problem.
two。 The inner class has direct access to all members of the external class, making the implementation more flexible.
See the example of greenhouse (greenhouse).
Inheritance of inner classes
The reference of the inner class to outer class object must be initialized, and there is no default object to join in its inherited class, and this association must be explicitly indicated using special syntax.
A class constructor that inherits from an inner class cannot be the default constructor, has a reference to outer class as a parameter, and must add an enclosingClassReference.super (); statement for compilation to pass.
Inner class can override? Inheriting outer class and overriding inner classes like overriding methods does not work, when the two inner classes are just two separate entities. You can explicitly specify the inheritance relationship of the inner class, and then implement polymorphism by overriding the method of base inner class. See example BigEgg2.
/ /: innerclasses/BigEgg2.java / / Proper inheritance of an inner class. Import static net.mindview.util.Print.*; class Egg2 {protected class Yolk {public Yolk () {print ("Egg2.Yolk ()");} public void f () {print ("Egg2.Yolk.f ()");}} private Yolk y = new Yolk (); public Egg2 () {print ("New Egg2 ()");} public void insertYolk (Yolk yy) {y = yy } public void g () {.F ();}} public class BigEgg2 extends Egg2 {public class Yolk extends Egg2.Yolk {public Yolk () {print ("BigEgg2.Yolk ()");} public void f () {print ("BigEgg2.Yolk.f ()");}} public BigEgg2 () {insertYolk (new Yolk ()) } public static void main (String [] args) {Egg2 e2 = new BigEgg2 (); e2.g ();} / * Output: Egg2.Yolk () New Egg2 () Egg2.Yolk () BigEgg2.Yolk () BigEgg2.Yolk.f () * / /: ~
Local inner class
Local inner classes (local inner class) cannot have access qualifiers; have access to local final variables and outer class all classes; can have named constructors; and cannot access outside methods.
In most cases, you can replace local inner classes with anonymous classes, unless:
1. A named constructor is required or the constructor needs to be overloaded
two。 Objects that require multiple inner classes
Use Local Inner class at this point.
This is the answer to the question about how to understand the inner classes in Java programming. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.