Summarize the usage and organization of Java internal classes, and analyze java

Source: Internet
Author: User

Summarize the usage and organization of Java internal classes, and analyze java

========================================================== ======================
Author: qiujuer
Blog: blog.csdn.net/qiujuer
Website: www.qiujuer.net
Open-source Library: Genius-Android
Reprinted please indicate the source: http://blog.csdn.net/qiujuer/article/details/43282699

-- Learning Open Source for open source; a beginner's mentality is shared with you!
========================================================== ======================

Collation

This article is a coincidence. It was suddenly found in use that day.JavaInternal class scoreStaticTo be honest, I usually use it, but I didn't notice it. I feel it is necessary to summarize it.

It is necessary to mention that this article is purely an analysis. If you have any additional information, please note in the comments that you are welcome to summarize.

Internal class location

public class A {class B {}public void pint() {class C {}new C();}public void pint(boolean b) {if (b) {class D {}new D();}}}
It can be seen from the code that the internal class can be defined in many places, commonly used in member variables (B)The method is also called a local internal class. (C), In scope (D)

From the above, it seems that I have never used the methods and scopes. This is wrong. Let's take a look at this:

public interface AInterface {void show();}public class B {public void show() {class Man implements AInterface {@Overridepublic void show() {}}Man man = new Man();man.show();}}
Two files are defined. One file is an interface class and the other is BFile; in BClass Show ()Method, we use the local internal class method to create a class Man, Man classInherit the interface and implement the method, and then use this class.

Why does the internal class have internal class permissions?

In my opinion, classes are mainly encapsulation, inheritance, and polymorphism. Of course, the callback idea is very important, and the appearance of internal classes is to simplify the problem of multiple inheritance.AClass, and cannot inherit from multiple other classes, but you need to use methods of other classes in use, this time the internal class will play a role; typical is the callback Implementation of event click.

So what are the permissions of internal classes?

As for the answer, you can see it in the code.

public class C {int a = 1;private int b = 2;protected int c = 3;public int d = 4;void a() {System.out.println("A:" + a);}private void b() {System.out.println("B:" + b);}protected void c() {System.out.println("C:" + c);}public void d() {System.out.println("D:" + d);}class D {void show() {int max = a + b + c + d;a();b();c();d();System.out.println("Max:" + max);}}public static void main(String[] args) {D d = new C().new D();d.show();}}
Running result:


It can be seen that the internal class D has full access permissions to Class C, which is equal to the whole body being stripped for you to see.

What if it is the opposite?

public class C {class D {private int a = 20;private void a(){System.out.println("D.A:" + a);}}void show(){D d = new D();d.a();System.out.println("D.A:" + d.a);}public static void main(String[] args) {new C().show();}}
Running result:


It can be seen that it is completely feasible to directly access the private method of private attributes. here it seems that the private restriction has expired. This reminds me of an interview I have seen before: in Java, when the private modifier will expire.

These two people are completely isolated from each other ~

Anonymous internal class

This is very common, especially in button-Click Event binding.

public class D {void initButton() {Button b1 = new Button();b1.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(Button v) {}});Button b2 = new Button();b2.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(Button v) {}});}}
Where:

    new OnClickListener() {@Overridepublic void onClick(Button v) {}}
Is the use of anonymous internal classes, OnClickListenerIs an interface class, the interface class cannot be directly NewAn instance. This is not the case here, NewThe class is anonymous, that is, there is no name, but the class implements OnClickListenerMethods In the interface class.

The callback part added above can be equivalent:

public class D {void initButton1() {Button b1 = new Button();b1.setOnClickListener(new Listener1());Button b2 = new Button();b2.setOnClickListener(new Listener2());}class Listener1 implements OnClickListener {@Overridepublic void onClick(Button v) {}}class Listener2 implements OnClickListener {@Overridepublic void onClick(Button v) {}}}
Here we first create a class, inherit from the interface, and then assign a value Button.

Let's talk about the differences and benefits between the two. This depends on the actual usage. If you have many buttons, but to avoid creating too many classes, you can create a callback class, then assign values to all buttons, but in the endOnClickMethod.

Many anonymous internal classes are used. The specific usage depends on the usage ~

Static internal class/static nested class

In fact, this should not be called an internal class because it does not have full permissions for the internal class and is basically the same as the general class. Why does this exist?

In my opinion, the existence of this class is to include class services for it. It means that this class can be independently served and is not known to external classes. For example:

public class E {private void show(){new A();}private static class A{}}
Class AUsed Static, So yes Static nesting class, Used here PrivateThe class can only be EClass; it cannot be instantiated in other files.

Can the external class be used in this case? No, right? Maybe you will sayE. javaCreate a folderA. java, And useProtectedBut it can be accessed in the same package or in the inherited class. This is only a special case.

Let's look at the permissions.

public class E {int a1 = 0;private int a2 = 0;protected int a3 = 0;public int a4 = 0;private void show(){A a =new A();System.out.print("b1:"+a.b1);System.out.print("b2:"+a.b2);System.out.print("b3:"+a.b3);System.out.print("b4:"+a.b4);}private static class A{int b1 = 0;private int b2 = 0;protected int b3 = 0;public int b4 = 0;private void print(){System.out.print("a1:"+a1);System.out.print("a2:"+a2);System.out.print("a3:"+a3);System.out.print("a4:"+a4);}}}
What is the result in this?


From the picture, we can see that the permission level is single direction. Static nested Class A is completely transparent to its contained Class E, but E is not transparent to Class.

Let's take a look at the method:


We can see the same situation. Why? Why is one more?StaticIs the modification completely different? It is well understood that two independent classes cannot be directly used. They must be referenced before they can call their attributes and methods.

We can adjust it like this.OK:

public class E {int a1 = 0;private int a2 = 0;protected int a3 = 0;public int a4 = 0;private void show() {A a = new A();System.out.print("b1:" + a.b1);System.out.print("b2:" + a.b2);System.out.print("b3:" + a.b3);System.out.print("b4:" + a.b4);a.b1();a.b2();a.b3();a.b4();}void a1() {}private void a2() {}protected void a3() {}public void a4() {}private static class A {int b1 = 0;private int b2 = 0;protected int b3 = 0;public int b4 = 0;void b1() {}private void b2() {}protected void b3() {}public void b4() {}private void print(E e) {System.out.print("a1:" + e.a1);System.out.print("a2:" + e.a2);System.out.print("a3:" + e.a3);System.out.print("a4:" + e.a4);e.a1();e.a2();e.a3();e.a4();}}}
Pass ETo solve the problem:


It can be seen that no error is reported now; it can run properly.

Hidden differences between the two

But what happened to the internal class at the beginning? Is it a ghost? The internal class above has not passed the reference. Why do I addStaticIt won't work?

Here we need to look at the bytecode. We should first create a simple internal class:

public class F {class A{}}
Is this simple enough? Don't say it's hard. Khan ~

Then we find the class file and view the bytecode:

The bytecode andF $Class bytecode.

Here is a sentence:Final F this $0;This is a very important sentence. This sentence appears in its internal class, which means that when you new an internal class, the current class is passed at the same time; therefore, the internal class can have full permissions of the current class and can use everything directly. This is because the current class has been passed in under the hidden circumstances.

Let's look at a simple static internal class:

public class G {static class A {}}
The only difference from the above is that Static. Now let's look at the bytecode:



It can be seen that eitherGClass, orG $There are no additional parts in class initialization, and no hidden information is passed into the current class. In this case, we do not have the access permission and need to pass the reference, it can be passed through the interface or completely, depending on the individual. So I addedStaticThe internal class of a class is more open (including classes) than the general class in terms of permissions. It is the same as the general class in terms of usage; so to be precise, it should be called static Nested classes.

Differences in Initialization

What should I do when a class includes both internal and static internal classes?

Both are directNew? Let's look at the Code:

public class H {int a = 1;public class A {public void Show() {System.out.print("a:" + a);}}public static class B {public void Show(H h) {System.out.print("a:" + h.a);}}public static void main(String[] args) {H h = new H();//A a = new A();A a1 = h.new A();B b = new B();//B b1 = h.new B();B b3 = new H.B();}}
The two annotations are not allowed, that is, they cannot run normally.

ABecause there is a hidden reference, it must beHTo initialize the instance.AAndBClass is becauseHClasses that exist in static mode, so you needNew h. B (); The reason for direct useNew B (), AndMainMethod inHClass, becauseHClass, so you can directly useHThe static attributes or methods of the class can be excluded from the following:"H..

Internal class inheritance

Direct inheritance:


The error is reported. Why? Because an H class needs to be passed in, we need to display the following points during inheritance:

public class I extends H.A{public I(H h){h.super();}}
That is, in the constructor, pass a reference of H and call the super () method of the H instance to instantiate the instance.
The usage should be as follows:

public static void main(String[] args) {        H h = new H();        I i = new I(h);    }

However, if you inherit its static nested class, you do not need to do this:

public class J extends H.B{}
In this case, OK.

Ah, it's almost done ~~ The entire internal class is almost like this. I wrote it for 3 hours and 42 minutes ~ Khan !!!!

If you have any written information, please add it ~~

Correct the error ~~


========================================================== ======================
Author: qiujuer
Blog: blog.csdn.net/qiujuer
Website: www.qiujuer.net
Open-source Library: Genius-Android
Reprinted please indicate the source: http://blog.csdn.net/qiujuer/article/details/43282699

-- Learning Open Source for open source; a beginner's mentality is shared with you!
========================================================== ======================

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.