In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of "Java internal class example analysis". The editor shows you the operation process through the actual case, and the operation method is simple, fast and practical. I hope this "Java internal class example analysis" article can help you solve the problem.
1. The concept and classification of internal classes
If a class is defined inside another class or inside the interface or inside the method, this class is called the inner class. We might as well call the inner class as the outer class. In addition to the inner class defined in the class, interface and method, there is also a special inner class, that is, using the keyword new to create an object of an anonymous class, and this anonymous class is actually an inner class. Specifically, it is an anonymous inner class that is often used to pass in constructor arguments to construct objects, such as the creation of PriorityQueue objects.
When a class is defined inside another class or interface, and there is no static modification, the inner class is called instance inner class. When static modification is used, this inner class is called static inner class (nested class). It defines a class inside the code block, especially inside the method body, this inner class is called local inner class or local inner class, and the other is the anonymous inner class mentioned above.
two。 Instance Internal Class 2.1 creation of instance Internal Class
The definition of the inner class of the instance is very simple, just define the inner part of the outer class directly. The problem is how to create an inner class object. first of all, we need to understand that the member variables and methods in the inner class and the outer class are equal, and they all belong to the outer class object (without static modification), so if you want the inner class object to have a peripheral class object, the first way to create an inner class object is to use a method to return an inner class object, and the type of the inner class object is OutClassName.InnerClassName. That is, the name of the peripheral class. Internal class name.
Public class Outer {class Inner1 {private String str; public Inner1 (String s) {this.str = s;} public String readStr () {return this.str;}} class Inner2 {private int val; public Inner2 (int I) {this.val = I } public int readVal () {return this.val;}} / / create inner class public Inner1 creatInner1 (String s) {return new Inner1 (s);} public Inner2 creatInner2 (int I) {return new Inner2 (I);} public static void main (String [] args) {Outer outer = new Outer () Outer.Inner1 inner1 = outer.creatInner1 ("Inner1"); Outer.Inner2 inner2 = outer.creatInner2 (2); System.out.println (inner1.readStr ()); System.out.println (inner2.readVal ());}} / / output:Inner12Process finished with exit code 02.2 use .this and .new
Of course, there are other ways to create an inner class, which is to use the object .new of the outer class to create an inner class object. The syntax is:
External class object. New inner class constructor
Public class Outer {class Inner1 {private String str; public Inner1 (String s) {this.str = s;} public String readStr () {return this.str;}} class Inner2 {private int val; public Inner2 (int I) {this.val = I } public int readVal () {return this.val;}} public static void main (String [] args) {Outer outer = new Outer (); Outer.Inner1 inner1 = outer.new Inner1 ("Inner1"); Outer.Inner2 inner2 = outer.new Inner2 (2); System.out.println (inner1.readStr ()); System.out.println (inner2.readVal ()) }} / / output:Inner12Process finished with exit code 0
The characteristics of the inner class are not only that, but the inner class can also be linked to the outer class. first of all, the creation of the inner class object of the instance depends on the reference of the outer class object, and the inner class of the instance has the same status as the member variables of the outer class. if you want to access the member variables and methods of the outer class (especially the variables of the same name) through the inner class object. In the inner class, you can use the outer class name .this to get the outer class object, and then use the obtained outer class object to use the variables and methods of the outer class.
Public class Outer {private String outStr; public Outer (String str) {this.outStr = str;} public void printOuter () {System.out.println (this.outStr);} class Inner {private String str; public Inner (String s) {this.str = s;} public String readStr () {return this.str } / / use .this to get parent object reference public Outer outer () {return Outer.this;}} public static void main (String [] args) {Outer outer = new Outer ("outerString"); Outer.Inner inner = outer.new Inner ("innerString"); Outer out = inner.outer (); out.printOuter () }} / / output:outerStringProcess finished with exit code 0
In fact, there are two this in the inner class object, which directly use this. Members get their own members of the inner class object, as above using the outer class name. This. The member gets the member of the outer class, that is, in the inner class, the this points to the reference of the inner class object itself, and the outer class name .this points to the reference of the outer class object.
These two this are of great use when the inner and outer class variable names are the same.
Public class Outer {public int a = 12; public int b = 16; public int c = 20; class Inner {public int a = 8; public int c = 48; public int d = 2; public void printVal () {System.out.println ("peripheral class variable a =" + Outer.this.a "); System.out.println (" peripheral class variable b = "+ Outer.this.b) System.out.println ("peripheral class variable c =" + Outer.this.c); System.out.println ("internal class variable a =" + this.a); System.out.println ("internal class variable c =" + this.c); System.out.println ("internal class variable d =" + this.d) }} public Inner creatInner () {return new Inner ();} public static void main (String [] args) {Outer outer = new Outer (); Outer.Inner inner = outer.creatInner (); inner.printVal ();}} / / output: peripheral class variable aqu 12, peripheral class variable bang 16, external class variable, internal class variable, d=2Process finished with exit code 0.
If the same name does not appear, you can obtain the member directly. You can not use the this mentioned above and appear with the same name. The member accessed directly is the inner class object by default.
2.3 Internal classes implement iterative printing
The inner class can have access to all elements of the outer class, so we can try to use the inner class to traverse the elements in the output outer class. although the members of the inner class and the outer class are equal, the inner class is also a class. it can also inherit classes and implement interfaces like peripheral classes.
Import java.util.Arrays;interface Selector {/ / determines whether to iterate over all elements public boolean end (); / / gets the current element public Object current (); / / iterates through the next element public void next ();} public class SequeArray {private Object [] items; private int usedSize; public SequeArray (int capacity) {items = new Object [capacity] } public void add (Object val) {if (usedSize = = items.length) items = Arrays.copyOf (items, 2 * usedSize); items [usedSize++] = val;} private class SequeSelector implements Selector {private int index; public boolean end () {return index = = usedSize;} public Object current () {return items [index] } public void next () {if (index < usedSize) index++;}} public SequeSelector sequeSelector () {return new SequeSelector ();} public static void main (String [] args) {SequeArray array = new SequeArray (10); for (int I = 0; I < 10; iTunes +) {array.add (iTun1) } / / upward transformation occurred Selector selector = array.sequeSelector (); while (! selector.end ()) {System.out.print (selector.current () + "); selector.next ();}} / / output:1 2 3 4 5 6 7 8 9 10 Process finished with exit code 02.4 inheritance of inner classes
Inheriting the inner class is a bit troublesome, because the constructor of the inner class must rely on references to the outer class, so you need a special syntax to explain the association between the inner class and the outer class:
The peripheral class references .super ()
For more information on how to use it, see the following code:
Public class Outer {class Inner {} class Person extends Outer.Inner {private String str; private int id; public Person (Outer out, String str, int id) {out.super (); this.str = str; this.id = id;} public void readVal () {System.out.println (this.str + this.id);}}
When the inner class is inherited, you need to pass a reference to the outer class into the constructor of the parent class and call super () to pass the compilation.
If the inner class inherits the external class, you can inherit it directly, and you don't need to be so troublesome.
When the program generates a bytecode file of a java file, it is named as the public external class $inner class.
Inner classes can be infinitely nested, and generally no one does.
3. Static inner class
A static inner class, also known as a nested class, adds a static keyword before the definition of the inner class of the instance, like this:
Public class Outer {static class Inner {}}
The difference between the static inner class and the instance inner class is that the static inner class belongs to the class rather than the object, so the creation of the static inner class does not depend on the external class object, which is one of the biggest differences from the instance inner class.
Public class Outer {static class Inner {private String str; public Inner (String s) {str = s;}} public static void main (String [] args) {Outer.Inner inner = new Outer.Inner ("I am a static inner class!") ; System.out.println (inner.str);}} / / output: I am a static inner class! Process finished with exit code 04. Anonymous inner class
We have seen the use of anonymous inner classes, that is, when creating PriorityQueue objects, small heaps are created by default, and you need to pass in a comparator to create large heaps.
PriorityQueue priorityQueue = new PriorityQueue (new Comparator () {@ Override public int compare (Integer o1, Integer o2) {return o1-O2;}})
As above, use the new keyword in the method to create an anonymous class object as an argument, in which the anonymous class is an anonymous inner class. The Comparator anonymous class object in the creation process inherits the required parameter type, in this case, the Comparator class.
If you use a custom type to pass in a priority queue, be sure to implement the comparator, which is most commonly implemented by anonymous inner classes and Lambda expressions.
Suppose I have an array of Person classes that need to sort their name, and if I don't use inner classes, I need to implement a comparator in the Person class.
Import java.util.Arrays;import java.util.Comparator;class Preson {public String name; public Integer id; public Preson (String name, Integer id) {this.name = name; this.id = id } @ Override public String toString () {return "Preson {" + "name='" + name +'\'+ ", id=" + id +'}';}} class PersonComparator implements Comparator {@ Override public int compare (Preson o1, Preson O2) {return o1.name.compareTo (o2.name) }} public class Main {public static void main (String [] args) {Preson preson1 = new Preson ("aboluo", 24); Preson preson2 = new Preson ("zhousi", 25); Preson preson3 = new Preson ("syyfjy", 2); Preson [] presons = {preson1, preson2, preson3}; Arrays.parallelSort (presons, new PersonComparator ()); System.out.println (Arrays.toString (presons)) }} / / output: [Preson {name='aboluo', id=24}, Preson {name='syyfjy', id=2}, Preson {name='zhousi', id=25}] Process finished with exit code 0
Using the inner class, the above code becomes:
Import java.util.Arrays;import java.util.Comparator;class Preson {public String name; public Integer id; public Preson (String name, Integer id) {this.name = name; this.id = id } @ Override public String toString () {return "Preson {" + "name='" + name +'\'+ ", id=" + id +'}';}} public class Main {public static void main (String [] args) {Preson preson1 = new Preson ("aboluo", 24); Preson preson2 = new Preson ("zhousi", 25) Preson preson3 = new Preson ("syyfjy", 2); Preson [] presons = {preson1, preson2, preson3}; Arrays.parallelSort (presons, new Comparator () {@ Override public int compare (Preson o1, Preson O2) {return o1.name.compareTo (o2.name);}}); System.out.println (Arrays.toString (presons)) }} / / output: [Preson {name='aboluo', id=24}, Preson {name='syyfjy', id=2}, Preson {name='zhousi', id=25}] Process finished with exit code 0
There is also a local inner class, that is, the class is defined in the method, which is basically not used, and the usage is as follows:
This is the end of public class Outer {public void func () {class Inner {/ /} about "Java inner class sample analysis". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
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.