Accumulation of internal classes in Java

Source: Internet
Author: User

Here static, which is decorated with the static keyword, includes classes, methods, blocks, fields.

Non-static, which is not modified with static.

Static has some features:

1. Globally unique, any modification is a global impact

2. Load only once, prior to non-static

3. The usage is not dependent on the instance object.

4. The lifecycle belongs to the class level, from the beginning of the JVM loading to the end of JVM uninstallation.

Refer to: http://blog.csdn.net/zhandoushi1982/article/details/8453522/.

For the differences between static inner classes (nested classes) and non-static inner classes, refer to:

Http://www.jb51.net/article/74838.htm

(1) Internal static classes do not need to have references to external classes. But non-static inner classes need to hold references to the external class.

(2) non-static inner classes can access static and non-static members of external classes. Static classes cannot access non-static members of external classes. He can only access static members of external classes.

(3) A non-static inner class cannot be created from an external class entity, and a non-static inner class can access the data and methods of the external class, because he is inside the outer class.

/* The following program demonstrates how to create a static inner class and a non-static inner class in Java */class outerclass{private static String msg = "Geeksforgeeks"; Static inner class public static class nestedstaticclass{//Static inner class can only access static members of external classes public void Printmessage () {//try to change msg to non-static     Compiler Error SYSTEM.OUT.PRINTLN ("Message from nested static class:" + msg); }}//non-Static inside class public class innerclass{//both static and non-static methods can access public void display () in non-static inner classes () {System.out.print    ln ("Message from Non-static nested class:" + msg); }}}} class main{//How to create an instance of a static inner class and a non-static inner class public static void Main (String args[]) {//Create an instance of a static inner class OUTERCLASS.NESTEDST    Aticclass printer = new Outerclass.nestedstaticclass ();      Create a static internal class non-static method Printer.printmessage ();        In order to create a non-static inner class, we need an instance of the outer class outerclass outer = new Outerclass ();    Outerclass.innerclass inner = outer.new innerclass ();    A non-static method called Inner.display () that calls a non-static inner class;    We can also combine the steps above to create an internal class instance Outerclass.innerclass InnerObject = new Outerclass (). New Innerclass (); Also we can now invoke the internalClass method Innerobject.display (); }}



A brief introduction to the anonymous inner class is made in the Java improvement-----, but there are many other details in the inner class, so this blog is derived. In this blog you can learn about the use of anonymous internal classes, what to note about anonymous inner classes, how to initialize anonymous inner classes, and why the formal parameters used by anonymous inner classes are final.

First, use anonymous inner class inner class

Anonymous inner class because there is no name, it is created in a somewhat strange way. The creation format is as follows:

[Java]View PlainCopy
    1. New parent class Constructor (parameter list) | Implement Interface ()
    2. {
    3. //Anonymous inner class part of the class body
    4. }

Here we see the use of anonymous inner classes we have to inherit a parent class or implement an interface, and of course only inherit one parent class or implement an interface. It also does not have the class keyword, because the anonymous inner class is a reference that uses new directly to generate an object. Of course, this reference is implicit.

[Java]View PlainCopy
  1. Public Abstract class Bird {
  2. private String name;
  3. Public String GetName () {
  4. return name;
  5. }
  6. public void SetName (String name) {
  7. this.name = name;
  8. }
  9. public abstract int fly ();
  10. }
  11. Public class Test {
  12. public void Test (Bird Bird) {
  13. System.out.println (Bird.getname () + "able to fly" + bird.fly () + "M");
  14. }
  15. public static void Main (string[] args) {
  16. Test test = new test ();
  17. Test.test (new Bird () {
  18. Public int Fly () {
  19. return 10000;
  20. }
  21. Public String GetName () {
  22. return "Wild Goose";
  23. }
  24. });
  25. }
  26. }
  27. ------------------
  28. Output:
  29. Geese can fly 10000 meters

In the test class, the test () method accepts a parameter of type bird, and we know that there is no way for an abstract class to be directly new, we must first have an implementation class in order to new out of its implementation class instance. Therefore, the anonymous inner class is used directly in the Mian method to create an bird instance.

Because an anonymous inner class cannot be an abstract class, it must implement its abstract parent class or all the abstract methods inside the interface.

For this anonymous inner class code can be split into the following form:

[Java]View PlainCopy
  1. Public class Wildgoose extends bird{
  2. Public int Fly () {
  3. return 10000;
  4. }
  5. Public String GetName () {
  6. return "Wild Goose";
  7. }
  8. }
  9. Wildgoose wildgoose = new Wildgoose ();
  10. Test.test (Wildgoose);

Here the system creates an object that inherits from the anonymous class of the bird class and transforms it into a reference to the bird type.

There is a flaw in the use of anonymous inner classes, that is, it can only be used once, when an anonymous inner class is created, it immediately creates an instance of the class, and the definition of the class disappears immediately, so the anonymous inner class cannot be reused. For the above example, if we need to use multiple internal classes within the test () method, it is recommended that you redefine the class instead of using an anonymous inner class.

Second, the matters needing attention

In the process of using anonymous inner classes, we need to pay attention to the following points:

1 . When using anonymous inner classes, we must inherit a class or implement an interface, but both cannot be combined, and can inherit only one class or implement an interface.

2 . The constructor cannot be defined in an anonymous inner class.

3 . No static member variables and static methods can exist in the anonymous inner class.

4 . The anonymous inner class is a local inner class, so all the limitations of the local inner class also take effect on the anonymous inner class.

5 . An anonymous inner class cannot be abstract, it must implement all the abstract methods of an inherited class or an implemented interface.

Iii. why the formal parameters used are final

Reference documents: http://android.blog.51cto.com/268543/384844

When we pass parameters to an anonymous inner class, the formal parameter must be final if it needs to be used in the inner class. That is , the parameter must be final when the formal parameter of the method is used inside the inner class.

Why does it have to be final?

First we know that after the internal class is successfully compiled, it produces a class file that is not the same class file as the external class, and only retains references to external classes. When an external class passes in a parameter that needs to be called by an inner class, it is called directly from the Java program's point of view:

[Java]View PlainCopy
  1. Public class Outerclass {
  2. public void display (final String name,string age) {
  3. class innerclass{
  4. void Display () {
  5. SYSTEM.OUT.PRINTLN (name);
  6. }
  7. }
  8. }
  9. }

From the above code, it seems that the name parameter should be called directly by the inner class. In fact, after the Java compilation, the actual operation is as follows:

[Java]View PlainCopy
  1. Public class Outerclass$innerclass {
  2. Public Innerclass (String name,string age) {
  3. This .  Innerclass$name = name;
  4. This .  Innerclass$age = age;
  5. }
  6. public void display () {
  7. System.out.println (This. Innerclass$name + "----" + this .  Innerclass$age);
  8. }
  9. }

Therefore, from the above code, the inner class is not directly invoke the parameters passed by the method, but instead uses its own constructor to back up the parameters passed in, its own internal method calls the actual time its own property rather than the external method passed in the parameters.

Until there's no explanation why it's final? The properties in the inner class and the parameters of the external method both look the same thing from the outside, but they are not, so they can be arbitrarily changed, that is, in the inner class my change to the property does not affect the external parameter, but this is not feasible from the programmer's point of view, After all, from the point of view of the program, these two are the same, if the inner class is changed, and the external method's parameters are not changed this is difficult to understand and unacceptable, so in order to maintain the consistency of the parameter, it is necessary to use final to avoid the formal parameter unchanged.

The simple understanding is that a copy reference, in order to avoid the reference value changes, such as by the external class method modification, and so on, resulting in the internal class resulting in inconsistent values, so use final to make the reference immutable.

Therefore, if an anonymous inner class is defined and you want it to use an externally defined parameter, the compiler will require that the parameter reference be final.

Iv. Anonymous Internal class initialization

We generally use constructors to do the initialization of an instance, but the anonymous inner class is not a constructor! So how do you initialize an anonymous inner class? Use Construction code blocks! The effect of creating a constructor for an anonymous inner class can be achieved by constructing a block of code.

[Java]View PlainCopy
  1. Public class Outclass {
  2. Public innerclass Getinnerclass (final int. Age,final String name) {
  3. return New Innerclass () {
  4. int Age_;
  5. String name_;
  6. //Construct code block to complete initialization work
  7. {
  8. if (0 < Age && Age < $ ) {
  9. Age_ = age;
  10. name_ = name;
  11. }
  12. }
  13. Public String GetName () {
  14. return name_;
  15. }
  16. public int getage () {
  17. return age_;
  18. }
  19. };
  20. }
  21. public static void Main (string[] args) {
  22. Outclass out = new Outclass ();
  23. Innerclass inner_1 = Out.getinnerclass (201, "Chenssy");
  24. System.out.println (Inner_1.getname ());
  25. Innerclass inner_2 = Out.getinnerclass (at "Chenssy");
  26. System.out.println (Inner_2.getname ());
  27. }
  28. }

Accumulation of internal classes in Java

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.