Four classifications and functions of Java inner classes
Internal class content analysis
Differentiation of inner classes
Internal classes include member internal class, local internal class, anonymous internal class and static internal class. Next, we will introduce them respectively.
Member inner class
It is the class that is located in the member position of the external class. Side by side with the properties and methods of external classes.
As a member of an external class, a member internal class can access private members or properties of the external class. (even if the external class is declared private, it is visible to the internal class that is inside.)
Use member inner classes to define properties that are not accessible in outer classes. In this way, the access rights of the external class are smaller than the private of the external class.
Note: inner class is a compile time concept. Once compiled successfully, it will become two completely different classes. For an external class named outer and an internal class named inner defined within it. After the compilation, there are two types: outer.class and outer$inner.class.
Code example
public class Demo1 {
innerclass in=new innerclass(); //Instantiate member inner class in the outer class of member inner class public void outf() { in.inf(); //Because in is an instance of a member's inner class, you can call } class innerclass{//Member inner class int y=0; public innerclass() {//Construction method of inner class of member } public void inf() { System.out.println("Inner class method y="+y); } } public static void main(String[] args) { Demo1 iDemo1=new Demo1(); iDemo1.outf(); Demo1.innerclass j= iDemo1.new innerclass(); //Non external class location member internal class instantiation method (i.e. first instantiate an external class) Demo1.innerclass k=new Demo1().new innerclass(); //Instantiation outer class and construction inner class j.inf(); }
}
Effect
Data security. If our inner class doesn't want to be easily accessed by anyone, we can choose to use private to decorate the inner class, so we can't access it through the way of creating objects. To access it, we only need to define a public decorated method in the outer class and call it indirectly. The advantage of this is that we can add some judgment statements in the public method to play the role of data security.
Local inner class
A class defined in a method or scope.
Static variables cannot be defined in a local inner class. You can access the local variables of the outer class (that is, the variables in the method), but the variables must be final.
Code example
public class Demo2 {
public outinterface action(String x) {//To return this class, you need to go through the interface, because the inner class does not exist in the outer scope class innerclass2 implements outinterface{ public innerclass2(String s) { s = x; System.out.println(s); } } return new innerclass2("do"); } public static void main(String[] args) { Demo2 demo2=new Demo2(); demo2.action("Local inner class"); }
}
interface outinterface {/ / is specially used for the operation of the parent interface for the up transformation of the local inner class
}
Local internal classes can only be instantiated within the scope of the method body. If you want to return the class in the method body, you need to transform up through the interface. (as code above)
- Effect
In some cases, some business logic needs to be processed temporarily. If these business logic is only used here and can be encapsulated into a class, there is no need to re create a file, so you can write a local internal class to handle it. Then, in my memory, the java proxy pattern is useful for local internal classes, which directly implement interfaces in methods and return proxy objects, which is simple and convenient.
Static inner class
Inner class of static field, side by side with static method.
Code example
public class Demo3 {
static int x=100; static class innerclass3 { void action() { x=1; //x must be a static field } public static void main(String[] args) { System.out.println("I'm a static inner class"); } }
}
Effect
Provide debugging function. I write the main method in the static inner class. After generating the. Class file, the debugging code is in the static inner class. When I delete the static inner class, others can still use my outer class.
Anonymous Inner Class
A class without a name is a simplified way to write internal classes.
Essence: in fact, it is a subclass anonymous object that inherits the class or implements the interface.
Code example
//Code example 1
public class Demo4 {
public Outinterface2 action() { //return new innerclass2(); ① return new Outinterface2() { //② private int i = 0; public int getvalue() { return i; } }; }
}
interface Outinterface2 {
}
class innerclass2 implements Outinterface2{//①
private int i = 0; public int getvalue() { return i; }
}
//Code example 2
interface Inner {
public abstract void show();
}
class Outer {
public void method(){ new Inner() { public void show() { System.out.println("HelloWorld"); } }.show(); }
}
class Test {
public static void main(String[] args) { Outer o = new Outer(); o.method(); }
}
//How can I call multiple methods in an anonymous inner class?
Inter i = new Inner() {/ / polymorphism, because new Inner() {} represents a subclass object of the interface
public void show() { System.out.println("HelloWorld"); }
};
The above codes ① and ② have the same function. This also explains the role of anonymous inner classes.
Effect
When we develop, we will see abstract classes or interfaces as parameters. At this time, what we need is a subclass object. If this method is called only once, we can use the format simplification of anonymous inner class.
Why to use inner class (this part is reprint, see the author and original link at the bottom of the article)
1, Encapsulation
As a class writer, we obviously need to make certain restrictions on the access rights of users of this class. We need to hide some operations that we don't want others to see. If our internal class doesn't want to be easily accessed by anyone, we can choose to use private to decorate the internal class, so we can't visit through the method of creating objects Ask, to access only need to define a public decorated method in the external class, indirect call.
public interface Demo {
void show();
}
class Outer {
private class test implements Demo { public void show() { System.out.println("Password backup file"); } } public Demo getInner() { return new test(); }
}
2, Implement multiple inheritance
As we learned before, java can't implement multiple inheritance. It can only inherit one class at a time. When we study interfaces, we mentioned that we can use interfaces to implement multiple inheritance, that is, an interface has multiple implementations, but there is also a little disadvantage here, that is, once an interface is implemented, all the methods in it must be implemented, sometimes it will appear It's a bit cumbersome, but using inner classes can solve these problems well.
public class Demo1 {
public String name() { return "BWH_Steven"; }
}
public class Demo2 {
public String email() { return "xxx.@163.com"; }
}
public class MyDemo {
private class test1 extends Demo1 { public String name() { return super.name(); } }
private class test2 extends Demo2 { public String email() { return super.email(); } }
public String name() { return new test1().name(); }
public String email() { return new test2().email(); }
public static void main(String args[]) { MyDemo md = new MyDemo(); System.out.println("My name:" + md.name()); System.out.println("My mailbox:" + md.email()); }
}
We write two classes Demo1 and Demo2 to be inherited, and two internal classes in MyDemo class. test1 and test2 inherit Demo1 and Demo2 classes respectively, so that multiple inheritance is indirectly implemented in MyDemo.
3, Using anonymous inner class to realize callback function
In Java, we usually write an interface, and then you implement the interface, and pass one object of the interface as a parameter to another program method, and then call your method through the interface. Anonymous inner class can well show this callback function.
public interface Demo {
void demoMethod();
}
public class MyDemo{
public test(Demo demo){ System.out.println("test method"); } public static void main(String[] args) { MyDemo md = new MyDemo(); //Here we use anonymous inner class to pass the interface object as a parameter to the test method md.test(new Demo){ public void demoMethod(){ System.out.println("Specific implementation interface") } } }
}
4, Solve the problem of inheriting and implementing the interface with the same name
Write an interface Demo
public interface Demo {
void test();
}
Write a class MyDemo
public class MyDemo {
public void test() { System.out.println("Parent class test Method"); }
}
The names of both methods are test. Write a test class below;
public class DemoTest extends MyDemo implements Demo {
public void test() { }
}
In this way, I'm a bit confused about how to distinguish whether this method is interface or inheritance, so we use internal classes to solve this problem
public class DemoTest extends MyDemo {
private class inner implements Demo { public void test() { System.out.println("Interface test Method"); } } public Demo getIn() { return new inner(); } public static void main(String[] args) { //test() method from calling interface DemoTest dt = new DemoTest(); Demo d = dt.getIn(); d.test(); //Call the inherited test() method dt.test(); }
}
//Operation results
test method of interface
test method of parent class
Note: the "why use inner class" part of this article is reprint, and the original source is as follows.
By BWH.Steven
Links: https://www.zhihu.com/question/26954130/answer/708467570
Source: Zhihu
The copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source.