Some concepts about inner classes in Java

Source: Internet
Author: User
Tags instance method modifiers

To put a class inside the definition of another class, the class defined inside the other class is called the inner class.

The function of the inner class:

(1). The inner class provides a better encapsulation that hides the inner class within the outer class and does not allow other classes in the same package to access the class.

(2). Inner class members can access private data of an external class directly, because an inner class is treated as its outer class member, and the members of the same class can access each other. However, an external class cannot access the implementation details of an inner class.

(3). Anonymous inner classes are used to create classes that need to be used only once.

(4). Internal analogy external classes can use more than three modifiers: private, Protected, static--external classes can not use these three modifiers.

(5). Non-static inner classes cannot have static members.

1. Non-static inner class

Defining an inner class is very simple, as long as you put one class inside another class to define it. The "Inside class" here includes any location in the class, even within a method, where the inner class defined inside the method is referred to as a local inner class.

A member inner class is a class member that resembles a member variable, a method, a constructor, and an initialization block, while a local inner class and an anonymous inner class are not class members.

There are two types of member inner classes: Static inner classes and non-static inner classes, which are static inner classes that use static decorated members inner classes, and non-static inner classes that do not use static modifiers.

Because an inner class is a member of its outer class, you can use arbitrary access controls such as private, protected, and public adornments.

The upper-level program unit of the outer class is a package, so he has only two scopes: within the same package and anywhere. The upper-level program unit of an inner class is an external class that has 4 scopes: the same class, the same package, the parent-child class, and any location, so you can use the four-in Access control permission.

public class Cow {private double weight;//external class two overloaded constructors public Cow () {}public Cow (double Weight) {this.weight=weight;} Defines a non-static inner class @suppresswarnings ("unused") private class cowleg{//Two instance variable of a non-static inner class private double length;private String color;//two overloaded constructors for non-static inner classes public Cowleg () {}public cowleg (double length,string color) {this.length=length;this.color= Color;} Public double GetLength () {return length;} public void SetLength (double length) {this.length = length;} Public String GetColor () {return color;} public void SetColor (String color) {this.color = color;} Instance methods for non-static inner classes public void info () {System.out.println ("Current leg color is:" +color+ ", High:" +length);// Accessing the private decorated member variable of the external class System.out.println ("The cow with the cow leg is heavy:" +weight);}} public void Test () {Cowleg c1=new Cowleg (1.12, "Black and White"); C1.info ();}                 public static void Main (string[] args) {Cow cow=new Cow (378.9); cow.test ();/* * Output: * Current leg color is: black and white, High: 1.12 * The cow's calf weight: 378.9 */}} 
The above program generates two class files after compiling, one is Cow.class and the other is Cow$cowleg.class, which is the class file of the external class cow, which is the class file of the inner class Cowleg, that is, the member inner class (including the static inner class, The class file for non-static inner classes is always in this form: Outerclass$innerclass.class.

In a non-static inner class object, a reference to the outer class object that it is parasitic on (when invoking an instance method of a non-static inner class, must have a non-static inner class instance, and a non-static inner class instance must be parasitic in an external class instance).

When a variable is accessed within a method of a non-static inner class, the system takes precedence within the method to find the local variable that is sufficient for the name, if it exists, if it is present, if it does not exist, to find out if there is a member variable of that name in the inner class in which the method exists, if that member variable is present; Find out if the member variable exists for that name in the outer class that contains the inner class, and if it does, use that member variable, and if it does not already exist, the system will have a compilation error: The variable is not found.

If the outer class member variable, the inner class member variable has the same name as the local variable of the method inside the inner class, it can be distinguished by using the this, the outer class class name.

public class Discernvariable {private String prop= "instance variable of the outer class";p rivate class inclass{private String prop= "instance variable of the inner class"; public void info () {String prop= "local variable";//through the external class class name. This.varname accesses the external class instance variable System.out.println ("instance variable value of the outer class:" + DiscernVariable.this.prop);//This.varname accesses the variable System.out.println of the Inner class instance ("instance variable value of the inner class:" +this.prop);// Direct access to local variable System.out.println ("value of local variable:" +prop);}} public void Test () {Inclass in=new inclass (); In.info ();} public static void Main (string[] args) {new discernvariable (). Test ();/* * Output: * instance variable value for external class: instance variable                      for external class Instance variable value of an inner class: The value of the instance variable                      local variable of the inner class: local variable */}}
An instance variable of an external class is accessed through the form of OuterClass.this.propName, and an instance variable of a non-static inner class is accessed through This.propname.

Members of non-static inner classes can access private members of external classes, but not in turn. Members of non-static inner classes are known only within the scope of non-static inner classes and cannot be used directly by external classes. If an external class requires access to a member of a non-static inner class, you must explicitly create a non-static inner class object to invoke access to its instance members.

public class Outer {private int outprop=9;class inner{private int inprop=5;public void Acessouterprop () {// Non-static inner classes can directly access the private member variable of the external class System.out.println ("Outprop Value of the outer class:" +outprop);}} public void Accessinnerprop () {///external class cannot directly access instance variables of non-static inner classes///code Compile Error//system.out.println ("Inprop Value of inner class:" +inprop);// To access an instance variable of an inner class, you must explicitly create an inner class object System.out.println ("Inprop value for the inner class:" +new Inner (). Inprop);} public static void Main (string[] args) {Outer out=new Outer (); Out.accessinnerprop ();/* * Output: * The Inprop value of the inner class: 5 */}}
The relationship between non-static inner class objects and external class objects: Non-static inner class objects must be parasitic in external class objects, while external class objects do not necessarily have to be parasitic among non-static inner class objects. Simply put, if there is a non-static inner class object, there must be an outer class object that is parasitic by it. However, when an external class object exists, the outer class object does not necessarily parasitic non-static inner class objects. Therefore, when an external class object accesses a non-static inner class member, the non-static ordinary inner class object may not exist at all. An external class object must exist when a non-static inner class object accesses an external class member.

Static methods of external classes, static code blocks cannot access non-static inner classes, including non-static inner classes that cannot be used to define variables, create instances, and so on, based on rules that static members cannot access non-static members. In summary, non-static inner classes are not allowed to be used directly in static members of external classes.

Java does not allow static variables to be defined in non-static inner classes.

There cannot be static methods, static member variables, static initialization blocks in non-static inner classes.

Static initialization blocks may not be available in non-static inner classes, but they can contain normal initialization blocks. Non-static is not tired of ordinary initialization blocks acting on the external class of the initialization block function exactly the same.

2. Static Inner class

If static is used to decorate an inner class, the inner class belongs to the outer class itself and not to an object of the outer class. Therefore, inner classes that use static adornments are referred to as class inner classes, and in some places they become static inner classes.

The Static keyword works by turning the members of a class into class-dependent, that is, the static decorated members belong to the entire class, not to individual objects. The upper-level program unit of an outer class is a package, so static decoration is not allowed, whereas the upper-level program unit of an inner class is an external class, and using the static adornment can make the inner class dependent on the outer class, rather than the external class instance, so the static keyword cannot decorate the outer class, but it can decorate the inner class.

A static inner class can contain static members, or it can contain non-static members. A non-static inner class cannot access an instance member of an external class, and can access only the class members of an external class, based on a rule where a static member cannot access a non-static member. Even an instance method of a static inner class cannot access an instance member of an external class, only the static member of the outer class.

A static inner class can contain static members, or it can contain non-static members. Static internal classes cannot access instance members of external classes, and can access only class members of external classes, depending on the rules for which static members cannot access non-static members. Even an instance method of a static inner class cannot access an instance member of an external class, only static members of an external class can be accessed.

A static inner class is a static member of an external class, so all methods of an outer class, all initialization blocks can use static inner classes to define variables, create objects, and so on.

External classes still do not have direct access to members of static inner classes, but you can use the class name of a static inner class as the caller to access the class members of a static inner class, or you can use a static inner class object as the caller to access the instance members of the static inner class.

public class Accessstaticinnerclass {static class staticinnerclass{private static int prop1=5;private int prop2=9;} public void Accessinnerprop () {//system.out.println (PROP1);//The above code has an error and should be changed to the following form//access to the class member of the static inner class through the class name System.out.println ( STATICINNERCLASS.PROP1);//system.out.println (PROP2);//The above code error, should be the following form//access the instance member of the static inner class through the instance System.out.println (new Staticinnerclass (). prop2);}}
Java also allows the definition of internal classes in the interface, the internal class defined in the interface by default using the public static modifier-the interface inner class can only be static inner class.

If you specify an access control character for an interface inner class, you can specify only the public access control, and the inner class defaults to the public access control permission if you define the interface's inner class to temporarily omit the access control.

Some concepts about inner classes in Java

Related Article

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.