Non-simple Java internal class

Source: Internet
Author: User

Cainiao learns Java and is now commercially available.

The so-called internal class is that the definition of a class is placed inside the definition of another class, such:

Public class outerclass {<br/> private int outerdata; <br/> //..... <br/> public class innerclass {<br/> private int innerdata; <br/> //...... <br/>}< br/>}

Internal classes should be regarded as a difficulty in Java learning. The reason why it is difficult is that I think there are two aspects: first, its syntax is more complicated than the other parts of Java, and there are many details that need attention; second, its application scenarios, that is, why does Java need such a thing and what benefits does it bring? If you cannot answer this question, it is difficult to use it in future practice even if you are familiar with its syntax. In my personal learning process, the second point has plagued me for a longer time.

This blog is mainly centered on these two difficulties.

For ease of understanding, I put all the static-related content in the internal class at the end of the entire article. Therefore, you can temporarily ignore the content at the beginning. Finally, I will explain why I want to do this.

 

First, explain some syntaxes.

 

As the previous code shows, internal classes are defined within a class. In this case, there are at least two points which are not the same as ordinary classes:

1. It embodies a code hiding mechanism and access control mechanism. At this point, it is like the concept of C ++ Nested classes;

2. It contains the this pointer of an external class. This is an important point to understand internal class features. With this pointer, the internal class can access all elements of the external class.

Combining these two points is the essence of the internal class.

 

Supplement 1:

IfInternal class declared as public
, This class name can be used outside the external class scope, but the method used must be:

Outerclass. innerclass

This is actually a bit of namespace. To use innerclass, yes, but always have to carry a prefix...

To create such an internal class instance, you need to use an external class instance. For example, if there is an outerclass instance, outerobject:
Outerclass. innerclass innerobject = outerobject. New innerclass ();

In this way, an internal class instance can be obtained outside the external class scope. The reason for this is that the instance of the internal class must contain the this pointer of an external class. If there is not an external class instance first, which of the following is this pointer?

If the internal class is declared as private
:

First, in Java, common classes cannot be modified by private. Therefore, only internal classes can be modified by private;

Second, if it is modified to private, the internal class is invisible outside the scope of the external class. Only external classes can use internal classes. In this way, an access control is implemented.

 

Supplement 2:

All elements of the external class can be accessed, that is, all member data and methods including public/private of the external class. For example, in the previous Code, innerclass can change the outerdata of outerclass:

Public class outerclass {<br/> private int outerdata; <br/> public class innerclass {<br/> private void func () {<br/> outerclass. this. outerdata = 1; <br/> //.......... <br/>}< br/>}

On the other hand, in reverse order, the external class also has access to all elements of the internal class, including private members and methods of the internal class:

Public class outerclass {</P> <p> public class innerclass {<br/> private int innerdata; <br/> //..... <br/>}< br/> Public void func () {<br/> innerclass innerobj = new innerclass (); <br/> innerobj. innerdata = 0; <br/> //......... <br/>}< br/>}

 

A special case of an internal class is the so-called local internal class, that is, defining an internal class in a member function of a class:

Public class outerclass {</P> <p> Public void func () {<br/> class innerclass {<br/> private int innerdata; </P> <p> //..... <br/>}</P> <p> innerclass innerobj = new innerclass (); </P> <p> //..... <br/>}< br/>}

The two features of internal classes introduced earlier look at local internal classes: From the Perspective of access control, local internal classes cannot be modified using public or private, it is only visible in this Member method. From the perspective of the relationship with the external class, it is not very different from the common internal class and can access any element of the external class. The only difference is that it can also access the local variables in this Member method, as long as the local variable is declared as final (this is a syntax detail, I will not expand it ).

 

After talking about so many syntaxes, I still can't see what the internal class is. Next, we will introduce a common scenario of internal classes, that is, internal classes inherit an interface or a base class. An external class member method can create an internal class instance, and then transform the instance to its interface/base class, for example:

//: Baseif. java <br/> Public interface baseif {<br/> //..... <br/>}< br/> //: outerclass. java <br/> public class outerclass {</P> <p> Public baseif getbase () {<br/> class innerclass implements baseif {<br/> //....... <br/>}</P> <p> return New innerclass (); <br/>}</P> <p> Public static void main (string [] ARGs) {<br/> outerclass outerobj = new outerclass (); <br/> baseif base = outerobj. getbase (); <br/>}< br/>}

In the final main function, an instance of the external class outerobj, by calling one of its member functions. getbase (), we finally obtain an instance of the baseif interface. But in fact, this instance is an internal class innerclass, which is invisible outside of the external class. However, because it is implemented by baseif, we can still throw its instance as the return value, then convert it to baseif to operate.

Of course, in this example, I still don't know what the internal class has to do. Don't worry, go down.

 

Because internal classes are frequently used in such scenarios, we have invented a simpler internal class for such scenarios. Anonymous internal class:

//. Baseif. java <br/> Public interface baseif {<br/> //..... <br/> Public void func (); <br/>}< br/> //. outerclass. java <br/> public class outerclass {</P> <p> Public baseif getbase () {<br/> return New baseif () {<br/> Public void func () {<br/> //....... <br/>}< br/>}; <br/>}</P> <p> Public static void main (string [] ARGs) {<br/> outerclass outerobj = new outerclass (); <br/> baseif base = outerobj. getbase (); <br/>}< br/>}

Anyone who sees this code for the first time will be depressed, such as me. Anyone who tries to read this code will be depressed for a long time, such as me.

However, if you know the previous application scenario, this Code is even easier to understand:

The "return New baseif" line of code indicates that a baseif object is to be returned, and a pair of "{}" appears, indicating that the braces are an anonymous internal class, this class implements baseif (if baseif is not an interface but a base class, it is not implemented but inherited ). The "Public void func" in braces is a member function that implements baseif again;

The reason for being anonymous is that this class does not have a name. The only thing we know is that it implements baseif;

 

So far, most of the syntax knowledge of internal classes has been completed. However, the most important question is still not answered:Why does Java provide the following benefits if it requires such a feature?

If you search for online articles, you may find the answer: Internal classes can help Java implement callback. Further, they apply to the event-driven architecture. But such an answer is still hard to understand.

To understand this, start with the simplest event-driven program:

// Eventif. java <br/> Public interface eventif {<br/> Public void execute (); <br/>}< br/> // controller. java <br/> public class controller {<br/> Public void addevent (eventif event) {<br/> //....... <br/> event.exe cute (); <br/> //...... <br/>}< br/>}

Once an event is added to the Controller, the Controller calls the execute method of the event.

 

Next, let's see how to instantiate some events. A direct method is to create some new classes which are implemented by eventif, such:

// Event1.java <br/> public class event1 implements eventif {</P> <p> Public void execute () {<br/> system. out. println ("this is event1"); <br/>}< br/>/controller. java <br/> public class controller {<br/> //........... <br/> Public static void main (string [] ARGs) {<br/> controller contler = new controller (); <br/> contler. addevent (New event1 (); <br/>}< br/>

 

There is no doubt that there is no problem in doing so. We can create an event1 instance and add it to the Controller as the addevent () parameter.

 

However, this also means that if any class wants to be called by the Controller as an event, it must be implemented by eventif. First, this is not necessarily appropriate. In addition, if event1 is not an interface but a base class, it is impossible for some Derived classes that have inherited other base classes to inherit eventif (Because Java does not support multiple inheritance ), therefore, these classes cannot be called by the Controller as events.

 

To solve this problem, it is time for internal classes to display power:

// Commonclass. java <br/> public class commonclass {<br/> //...... </P> <p> Public eventif getbase () {<br/> class event2 implements eventif {<br/> Public void execute () {<br/> system. out. println ("this is event2"); <br/>}</P> <p> return New event2 (); <br/>}< br/> // controller. java <br/> public class controller {<br/> Public void addevent (eventif event) {<br/> //....... <br/> event.exe cute (); <br/> //...... <br/>}</P> <p> Public static void main (string [] ARGs) {<br/> controller contler = new controller (); <br/> commonclass OBJ = new commonclass (); <br/> contler. addevent (obj. getevent (); <br/>}< br/>

Regardless of the form of commonclass, the base class or interface inherited. I can use an internal class so that one of its member functions can return an eventif implementation. In this Code, the result of obj. getevent () is an instance of the internal class, which is also an implementation of eventif. The instance of this internal class is equivalent to the OBJ replacement being put into the controller. It can be called a "substitute" because the instance of this internal class can access any member and method in the OBJ of the commonclass instance.

 

Using an anonymous internal class looks simpler:

// Commonclass. java <br/> class commonclass {<br/> //...... </P> <p> Public eventif getevent () {<br/> return New eventif () {<br/> Public void execute () {<br/> system. out. println ("this is anonymous event"); <br/>}< br/>}; <br/>}< br/> // controller. java <br/> public class controller {<br/> Public void addevent (eventif event) {<br/> //....... <br/> event.exe cute (); <br/> //...... <br/>}</P> <p> Public static void main (string [] ARGs) {<br/> controller contler = new controller (); <br/> commonclass OBJ = new commonclass (); <br/> contler. addevent (obj. getevent (); <br/>}< br/>}

 

I can also do better. A class implements two different events:

// Light. java <br/> public class light {<br/> private Boolean status = false; </P> <p> Public eventif lightonevent () {<br/> class onevent implements eventif {<br/> Public void execute () {<br/> If (! Status) {<br/> Status = true; <br/> system. out. println ("light on"); <br/>}</P> <p> return New onevent (); <br/>}</P> <p> Public eventif lightoffevent () {<br/> class offevent implements eventif {<br/> Public void execute () {<br/> If (Status) {<br/> Status = false; <br/> system. out. println ("light off"); <br/>}</P> <p> return New offevent (); <br/>}< br/> // controller. java <br/> public class controller {<br/> Public void addevent (eventif event) {<br/> //....... <br/> event.exe cute (); <br/> //...... <br/>}</P> <p> Public static void main (string [] ARGs) {<br/> controller contler = new controller (); <br/> light alight = new light (); <br/> contler. addevent (alight. lightonevent (); <br/> contler. addevent (alight. lightoffevent (); <br/>}< br/>}

The light class has two member functions that return different events. In addition, the execute () method of these events also changes the private data of light.

 

Therefore, you can say that it is very easy to implement with the Internal event-driven model. You can also say that the biggest benefit of the internal class is that it can achieve the same effect as multi-inheritance. In my opinion, both of them are actually correct and complement each other.

 

Finally, let's talk about the internal class modified by static.

The reason for putting it at the end, and I am not willing to elaborate, is that the internal class modified by static has lost its vitality as a castrated animal. Because the static internal class does not contain the this pointer of the external class, it cannot access the members of the External class. Therefore, internal classes bring huge benefits and internal classes are not available in applicable scenarios. I prefer to consider static internal classes separately, rather than confusing them with common internal classes.

 

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.