Java internal class analysis, Java Class Analysis

Source: Internet
Author: User

Java internal class analysis, Java Class Analysis
I. Introduction

Currently, as an intern in Android development, more and more developers are found to be unable to use it, such as the use of internal classes, therefore, after searching for materials on the Internet and summarizing them, I would like to share with you a blog post. If anything is inappropriate, I hope to point out it.

2. Internal class internal class refers to defining another class inside an external class, which is a concept during compilation. Once the compilation is successful, the internal class and the external class will become completely different, but the internal class will be prefixed with the class name and $ symbol of the external class, if an outer class defines an inner internal class, the outer is generated after compilation. class and outer $ inner. so the member variables and methods of the internal class can be the same as those of the external class. From the definition of internal classes, internal classes seriously damage the good code structure. Why should we use internal classes? Because internal classes can use member variables (including private ones) of external classes without generating external class objects, this is the only advantage of internal classes. Iii. Classification of internal classes and examples internal classes can be divided into member Internal classes, local internal classes, static internal classes, and anonymous internal classes. The following describes each internal class: (1) member internal class

As a member of an external class, it is in parallel with the attributes and methods of the external class. All members of the external class can be accessed in the internal class of the member. When the variables of the external class are the same as those of the internal class, the external class name is used. this. variable names can be called by external class variables. If there are no repeated variables, you can use them directly. You can access static internal classes in common external class methods to obtain new internal class objects of members and then directly call the methods. In static external class methods, you must first create external class objects, then call the external Class Object Name. new internal class to obtain member internal class objects.

Static variables cannot be defined in the internal class of a Member, because the internal class of a member must first be created to create its own class.

The internal class of a member can use the private members and attributes of the external class, and define the inaccessible attributes in the external class, in this way, the external class has lower access permissions than the external class's private.

The sample code is as follows:

/***** @ ClassName: MemberInnerClass * @ Description: Member internal class * @ author ADAM * @ date 9:20:28, January 1, July 25, 2014 **/public class MemberInnerClass {private int I = 0; public class Inner {// The internal class of the member can be added with the permission modifier int I = 3; public void print () {System. out. println (I); // The output is the I of the internal class and the value is 3System. out. println (this. i); // The output is the I of the internal class and the value is 3System. out. println (MemberInnerClass. this. i); // output I of the external class, value: 0} public void print () {(new Inner ()). print (); // external class common method call Member internal class direct new internal class call} public static void main (String [] args) {(new MemberInnerClass ()). new Inner ()). print (); // call the internal class of the member in the static method of the external class first, and then call the new internal class }}

(2) Local internal class

That is, the internal class defined in the method is similar to the local variable. The modifier public or private is not added before the local internal class, and its range is the code block that defines it. Static variables cannot be defined in local internal classes. You can access variables in external classes (that is, methods), but the variables must be final. When the name of a local internal class and an external class is renamed, the calling method is the same as that of the member's internal class. to access a local internal class, you must first have an external class object.

A local internal class cannot be directly generated outside the class (to ensure that the local internal class is invisible to the outside ). To use a local internal class, you need to generate an external class object. The object then calls the method before calling the method. The internal class achieves a forced weak coupling with the interface. The local internal class is used to implement the interface and the interface type is returned in the method to make the local internal class invisible, shield the visibility of the implementation class.

The sample code is as follows:

/***** @ ClassName: LocalInnerClass * @ Description: Local internal class * @ author ADAM * @ date 10:36:26, January 1, July 25, 2014 **/public class LocalInnerClass {private int j = 3; private int I = 2; public void test () {MemberInnerClass memberInnerClass = new MemberInnerClass (); // to access the internal class of a Member in another class, you can only access the internal class of the member if its modifier is public. // otherwise, the compilation is incorrect, that is, the internal class of the member can have lower permissions than the private class. new Inner (); final int I = 0; class Inner {// do not add private modifier here, otherwise the compilation error int I = 1; public void print () {System. out. println (j); modifier; otherwise, the System is incorrectly compiled. out. println (I); // at this time, the I of the local internal class is output. variables in the external method can only call System by passing parameters. out. println (LocalInnerClass. this. i); // at this time, the output is I} Inner inner Inner = new inner () in the external class; // The local internal class can only be instantiated in the method and called Inner. print ();} public static void main (String [] args) {(new LocalInnerClass ()). test ();}}

Local internal classes can be defined not only in methods but also in scopes. Two Thinking in Java examples are provided below

Defined in the method:

public class Parcel4 {     public Destination destination(String s) {         class PDestination implements Destination {             private String label;              private PDestination(String whereTo) {                 label = whereTo;             }              public String readLabel() {                 return label;             }         }         return new PDestination(s);     }      public static void main(String[] args) {         Parcel4 p = new Parcel4();         Destination d = p.destination("Tasmania");     } } <span style="line-height: 1.3em; font-family: 'Courier New', monospace; background-color: inherit;"> </span>

Defined in scope:

public class Parcel5 {     private void internalTracking(boolean b) {         if (b) {             class TrackingSlip {                 private String id;                 TrackingSlip(String s) {                     id = s;                 }                 String getSlip() {                     return id;                 }             }             TrackingSlip ts = new TrackingSlip("slip");             String s = ts.getSlip();         }     }      public void track() {         internalTracking(true);     }      public static void main(String[] args) {         Parcel5 p = new Parcel5();         p.track();     } } 

Local internal classes are compiled like other classes, but the scopes are different. They can only be used within the scope of the method or condition. If these scopes are exceeded, they cannot be used.

(3) static internal class

Static internal classes are also called nested internal classes. They are defined in the class and can be static or non-static members outside any method, it can be modified by public or private modifiers. Generally, it can be called conveniently. It can only access static members in external classes. When an external class accesses a static member in a static internal class, it directly uses an internal class. static member. When a non-static member of a static internal class is accessed, the static internal class is instantiated before being accessed through an object.

Generating a static internal class does not require external Class Object members, which is different from the internal class of the member. Common internal classes cannot have static methods and attributes, nor contain Nested classes, objects of static internal classes can be directly generated: External classes. internal Class Object Name = new external class. internal class ()

Note: When a method name conflict occurs between a class and an interface (or an interface), you must use an internal class. An interface cannot fully implement multi-inheritance. An interface can be used with an internal class to implement real multi-inheritance.

The sample code is as follows:

/***** @ ClassName: StaticInnerClass * @ Description: static internal class * @ author ADAM * @ date 10:37:04, January 1, July 25, 2014 **/public class StaticInnerClass {private int I = 1; public static int j = 1; public int k = 0; public static class Inner {private int I = 0; private static int j = 0; // static and non-static members can be defined. public static void print () {// System. out. println (k); // compilation error. Do not call the non-static member System in the external class. out. println (new StaticInnerClass (). i); // to access non-static member variables in the external class, you must first instantiate the external class System. out. println (j); System. out. println (new StaticInnerClass (). j); // static internal class use static members in the external class} public static void main (String [] args) {Inner. print (); // The internal class name directly when the external class static method or non-static method calls static members in the static internal class. the member can be StaticInnerClass. inner inner = new StaticInnerClass. inner (); // The instantiation of static internal classes does not need to be instantiated first. out. println (inner. i); // when accessing non-static members in a static internal class, the static internal class needs to be instantiated first }}

The sample code for implementing multi-inheritance through internal classes is as follows:

/***** @ ClassName: penpencil * @ Description: Pen class * @ author ADAM * @ date 10:42:59 on January 1, July 25, 2014 **/public abstract class penpencil {public abstract void write ();} /***** @ ClassName: Eraser * @ Description: eraser class * @ author ADAM * @ date 10:43:28 on April 9, July 25, 2014 **/public abstract class Eraser {public abstract void erase () ;}/ ***** @ ClassName: pencilWithEraser * @ Description (); private MyEraser eraser = new MyEraser (); private class mypencer extends pencer {// inherit pen class @ Overridepublic void write () {System. out. println ("To Write") ;}} private class MyEraser extends Eraser {// inherits the Eraser class @ Overridepublic void erase () {System. out. println ("To Erase") ;}// this class's own method calls the method in the inheritance class public void write () {penpencil. write ();} public void erase () {eraser. erase ();} public static void main (String [] args) {PencilWithEraser pencilWithEraser = new PencilWithEraser (); pencilWithEraser. write (); pencilWithEraser. erase ();}}

(4) Anonymous internal classes are used to inherit other classes or implement interfaces. They do not need to add additional methods, but only override or implement the inherited methods. They are also used only to get an object instance, you do not need to know the actual type. In this case, the class name is meaningless and does not need to be used.
The sample code is as follows:

/***** @ ClassName: AnonymousInnerClass * @ Description: anonymous internal class * @ author ADAM * @ date 10:38:25, January 1, July 25, 2014 **/public class AnonymousInnerClass {public void click (OnClickListener onClickListener) {System. out. println ("click, click");} public static void main (String [] args) {AnonymousInnerClass anonymousInnerClass = new AnonymousInnerClass (); anonymousInnerClass. click (new OnClickListener () {// directly new the anonymous internal class without saving the object. It is generally used to inherit other classes or implement the interface @ Overridepublic void onClick () {System. out. println ("Inner Click ");}});}}

Iv. Conclusion: as we are still in the learning stage, the most widely used internal classes are internal and anonymous internal classes, therefore, it is not very profound to have a very detailed understanding of the use cases of various internal classes and the role of smaller access permissions involved. Further learning will be done later, I also hope that my friends who have read this blog post can also provide some other insights or additional or recommended learning materials. This blog post also draws on the relevant information from the experts and encyclopedias on the Internet, thanks for the manual coding and verification.




Java internal class

In java, there is a kind of class called inner class, also known as nested class, which is defined inside other classes. An internal class is a member of its external class. Like other members, it can directly access the data and methods of its external class. However, compared with external classes, only public and default modifiers are different. An internal class can be any modifier as a member. During compilation, the internal class name is OuterClass $ InnerClass. class.

1. Internal class Access Data Variables
In some cases, when the variables defined in the internal class are the same as those in the external class, how can we ensure correct access to every variable?

1.1 calling internal class methods directly from external classes in main

Class Outer
{
Private int index = 10;
Class Inner
{
Private int index = 20;
Void print ()
{
Int index = 30;
System. out. println (this); // the object created from the Inner
System. out. println (Outer. this); // the object created from the Outer
System. out. println (index); // output is 30
System. out. println (this. index); // output is 20
System. out. println (Outer. this. index); // output is 10
}
}

Void print ()
{
Inner inner = new Inner (); // get internal class reference
Inner. print ();
}
}

Class Test
{
Public static void main (String [] args)
{
Outer outer = new Outer ();
Outer. print ();
}
}
Here, the internal class Inner keyword this points to the internal class Inner object. to point to the external class object, you must add the external class name before the this pointer, indicates that this is the debris that points to the external class structure, such as Outer. this.

1.2 explicitly returning internal class references in main

Class Outer
{
Private int index = 10;
Class Inner
{
Private int index = 20;
Void print ()
{
Int index = 30;
System. out. println (index );
System. out. println (this. index );
System. out. println (Outer. this. index );
}
}

... The remaining full text>

What are the internal and external classes in java?

External class, internal class, Anonymous class, external class is the class A {} class B {}, internal class: class A {class B {}}, B can directly use the member variables of the class containing it. The internal class cannot be called by classes other than the inclusion class; there is also an anonymous class, the internal class classA {new {}} also omits the definition class name to directly define the method and use, this applies to the code is relatively simple and this class does not need to be called by other 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.