Some special classes and interfaces in Java, and special methods for creating instances

Source: Internet
Author: User

Java has some special classes, in the teaching material is not deep, but it is very useful, here to summarize, the inside of the use of the content of the online search, here to express thanks.

First, members of the internal class

A member inner class is another class defined inside a class that belongs to a member of the class on which it is called a member inner class. You can think of this class as a member, a member that can be instantiated. The main role of this class is to replace the structure of the function, when a class to use a member is a struct type, but the structure is not universal, at this point can be declared as an inner class, which solves the problem of the structure.

Note: An inner class is a compile-time concept that, once compiled successfully, becomes a completely different class. For an external class named Outer and its internally defined inner class named inner. There are two classes of Outer.class and Outer$inner.class after the compilation is complete. Therefore, the member variable/method name of the inner class can be the same as the outer class.

Members of the inner class and members of the class have four access rights (the top-level class can only be declared as public or default), the permission and the member's permission definition is consistent, you can treat the inner class as a member. Inner classes have their own unique way of creating instances.

Create an instance of the member's inner class inside the outer class:innerclass innerclass = this.new innerclass ();

  Create an instance of an inner class outside the outer class:outerclass.innerclass = (new Outerclass ()). New Innerclass (); (Note: Must be a perimeter class object. New, not the perimeter class. New)

accessing members of an external class in an inner class:Outerclass.this.member;

  The class is characterized by the ability to use all members and methods of an external class directly, even if the members and methods in the outer class are private. While the outer class accesses all member variables/methods of the inner class, it needs to be fetched through the object of the inner class. It is important to note that the member inner class cannot contain static variables and methods. The principle is that because the member inner class needs to create an external class before it can create its own.

  It is recommended that you use Getinnerclass () to get inside objects, rather than using the above method of creation, especially if the inner class has only the default constructor.

Second, local internal class

A local inner class, which refers to an inner class definition within a method and scope. Thinking in Java gives such two examples:

1. Define within the method:

 Public classParcel4 { PublicDestination Destination (String s) {classPdestinationImplementsDestination {PrivateString label; Privatepdestination (String whereto) {label=Whereto; }               PublicString Readlabel () {returnlabel; }         }         return NewPdestination (s); }       Public Static voidMain (string[] args) {Parcel4 P=NewParcel4 (); Destination D= P.destination ("Tasmania"); } } 

2. Defined in scope:

 Public classParcel5 {Private voidInternaltracking (Booleanb) {if(b) {classTrackingslip {PrivateString ID; Trackingslip (String s) {ID=s; } String Getslip () {returnID; }} trackingslip TS=NewTrackingslip ("Slip"); String s=Ts.getslip (); }     }       Public voidTrack () {internaltracking (true); }       Public Static voidMain (string[] args) {Parcel5 P=NewParcel5 ();     P.track (); } } 

Local inner classes are compiled just like other classes, but only in different scopes, only within the scope of the method or condition, and cannot be referenced after exiting these scopes.

Third, static inner class (nested inner Class)

The static inner class is the inner class that is decorated as static. An inner class declared as static does not require a connection between an inner class object and an external class object, which means that we can refer directly to Outer.Inner, which means that you do not need to create an external class or create an inner class.

There is another difference between nested classes and ordinary inner classes: ordinary inner classes cannot have static data and static properties, and cannot contain nested classes, but nested classes can. Nested classes cannot be declared private, and are generally declared public for easy invocation.

At the same time, the static inner class can have non-static members, this time the static inner class can be considered as a member inner class, you can create an instance. A static inner class is a member that is declared as static internally, and in other classes, only through the external class name. The internal class name, which is referenced by a member name, is not an object that can be passed through an external class. The internal class name is not the same as the static members of the external class.

Inside a static class, you cannot access external non-static members, but you can create an instance of an external class just as you would a normal static method.

Iv. Anonymous Internal classes

This is a common method of declaring in Android, which can effectively reduce the complexity of your code.

Sometimes I prefer to use an anonymous inner class to avoid naming the inner class, because it has no name. For example:

(Button) Findviewbyid (R.id.start)). Setonclicklistener (new  Button.onclicklistener () {     @Override       Public void OnClick (View v) {         new  Thread () {              @Override             publicvoid  Run () {                 //            }          }.start ();     

This is in Android for a button to add click events, rewrite the Botton.onclicklistener () class of the OnClick method, to achieve their own needs.

Anonymous inner classes are not accessible modifiers. It is important to note that the new anonymous class, the class, is defined first.

 Public classOuter { Public Static voidMain (string[] args) {Outer Outer=NewOuter (); Inner Inner= Outer.getinner ("Inner", "GZ");     System.out.println (Inner.getname ()); }       PublicInner Getinner (Finalstring name, String city) {         return NewInner () {PrivateString nameStr =name;  PublicString GetName () {returnnameStr;     }         }; } }  //note, the compile-time prompt class Inner cannot be found/*interface Inner {String getName ();}*/ 

In this example, note the formal parameter of the method of the outer class, the parameter must be final when the parameter of the method being used is required to be inside the inner class. You can see that the parameter name is already defined as final, and the formal parameter city is not used without being defined as final. Why should it be defined as final?

"This is a compiler design problem and it's easy to understand if you understand how Java is compiled.   First, when the inner class is compiled, it generates a separate inner class of the. class file, which is not in the same class file as the external class.   When an external class is called by an inner class, it is called directly from the Java program's point of view, for example:  public void Dosome (final String a,final int b) {    Class Dosome{public void Dosome () {System.out.println (a+b)}};    dosome some=new dosome ();    some.dosome ();  }   from the code it seems that the internal class directly calls the A and B parameters, but actually not, after the Java compiler compiles the actual operation code is  class outer$dosome{    Public Dosome (final String a,final int b) {   this. Dosome$a=a;    this. Dosome$b=b;  }    public void Dosome () {   system.out.println (this). Dosome$a+this. DOSOME$B);  }  }   from the above code, the inner class is not the parameter that calls the method directly, but the inner class backs up the passed-in arguments through its own constructor to the inside, and its own internal method call is actually its own property rather than the parameters of the external class method.   So it's easy to understand why you want to use final, because the two look the same thing from the outside, actually not, if the internal classes get rid of the values of these parameters can not affect the original parameters, but this has lost the parameter consistency, Because from the programmer's point of view they are the same thing, if the programmer in the design of the internal class to break the value of the parameter, but the external call and found that the value has not been broken, which makes it very difficult to understand and accept, in order to avoid this embarrassing problem exists,So the compiler designer sets the parameters that internal classes can use to be final to avoid the existence of this inexplicable error. ” (A simple understanding is that copy references, in order to avoid changes in the reference value, such as by the external class method modification, etc., resulting in the internal class resulting in inconsistent values, so the final to make the reference immutable)   Because anonymous inner class, no name, is with the default constructor, no parameters, if you need parameters? You need this class with a constructor with parameters:
 Public classOuter { Public Static voidMain (string[] args) {Outer Outer=NewOuter (); Inner Inner= Outer.getinner ("Inner", "GZ");     System.out.println (Inner.getname ()); }       PublicInner Getinner (Finalstring name, String city) {         return NewInner (name, city) {PrivateString nameStr =name;  PublicString GetName () {returnnameStr;     }         }; } }  Abstract classInner {Inner (string name, String city) {System.out.println (city); }      AbstractString getName ();} 

Note here that the formal parameter city, because it is not used directly by the anonymous inner class, is used by the constructor of the abstract class inner, so it does not have to be defined as final.

The anonymous inner class can achieve the same effect as the constructor by initializing the instance:

 Public classOuter { Public Static voidMain (string[] args) {Outer Outer=NewOuter (); Inner Inner= Outer.getinner ("Inner", "GZ");         System.out.println (Inner.getname ());     System.out.println (Inner.getprovince ()); }       PublicInner Getinner (FinalString name,FinalString City) {         return NewInner () {PrivateString nameStr =name; PrivateString Province; //Instance Initialization            {                 if(City.equals ("GZ") ) {province= "GD"; }Else{province= ""; }             }               PublicString GetName () {returnnameStr; }               PublicString getprovince () {returnProvince;     }         }; } }  InterfaceInner {String getName (); String getprovince (); } 

V. Inheritance of internal classes

The inheritance of the inner class refers to the inner class being inherited, the ordinary class extents inner class. And this time the code to be a bit special to deal with, specifically, see the following examples:

 Public classInheritinnerextendsWithinner.inner {//Inheritinner () is not compiled, be sure to add a formal parameterInheritinner (Withinner wi) {wi.Super(); }       Public Static voidMain (string[] args) {Withinner wi=NewWithinner (); Inheritinner obj=NewInheritinner (WI); } }  classWithinner {classInner {}}

You can see that the subclass's constructor uses the outer class object of the parent class. Super (); This object needs to be created from the outside and passed to the formal parameter.

As for the overload of the inner class, it is very complicated to feel thinking in Java, and it should be seldom in the ordinary application, because it is a bit difficult to understand and unclear. and the inner class and the closure between the things, temporarily put down, look later.

Attach another article: "Doubts" appreciate the "inside" of the Java inner class to understand how the internal classes are handled at compile time.

The above is from the network, thanks to the original author.

The special place of inner class and internal interface.

1, as the characteristics of the type

The inline type cannot have the same name as the outer type.

The inner class can declare member variables and member methods, and inner class members can have the same name as external class members.

An inner class can inherit from a parent class or implement an interface.

An inner class can be declared as an abstract class, but the abstract class must be inherited by another inner class, and the internal interface must be implemented by another inner class.

2, as a member of the characteristics

Use the dot operator to refer to an inline type.

As a member, the inline type trusts each other with its outer type to access all members of the other party.

The inner class has four access control permissions for members in the class. You can consider the accessibility control permissions of members in an inner class when the inner class can be accessed.

Internal interfaces are always static, declaring inner classes to be static, static inner classes capable of declaring static member methods, but cannot refer to instance members of external classes. A non-static inner class cannot declare a static member.

Vii. execute some statements directly when creating an instance of a class

The anonymous class above is equivalent to overriding or implementing a method when creating a class, and a usage is to execute some of the statements in the class directly when creating an instance object of the class, which is equivalent to the object execution method that directly references the class. Such as:

        New son ("QQQ", 1)        {            {                = 9;            }        };

Nested inside a statement block. What is written outside the inner statement block is used when creating an anonymous class, overriding the parent class method directly, and internally nesting a statement block that is equivalent to B in the statement block. Age=9 This code, you can also directly execute the method in son, you can make the code look more concise. PS: The use of curly braces also allows you to directly assign the value {1,2,3,4} when creating an array.

Viii. creating an instance object with reflection

Some special classes and interfaces in Java, and special methods for creating instances

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.