[Java development path] (24) Internal classes

Source: Internet
Author: User

[Java development path] (24) Internal classes

In Java, a class can be defined in another class or a method. Such a class is called an internal class. In a broad sense, internal classes generally include these four types: member Internal classes, local internal classes, anonymous internal classes, and static internal classes. The following describes the usage of these four internal classes.

1. Member internal class

A member internal class is a class defined in another class.


  1. package com.qunar.fresh;
  2.  
  3. /**
  4. * Created by xiaosi on 16-3-29.
  5. */
  6. public class Circle {
  7. private double radius;
  8.  
  9. public Circle(double radius) {
  10. this.radius = radius;
  11. }
  12. // Internal class
  13. class Draw{
  14. public void drawCircle(){
  15. System.out.println("Circle---->" + radius);
  16. }
  17. }
  18.  
  19. public Draw getDrawInstance(){
  20. return new Draw();
  21. }
  22.  
  23. public static void main(String[] args) {
  24. Circle circle = new Circle(12.5);
  25. circle.getDrawInstance().drawCircle(); // 12.5
  26. }
  27. }

Circle is called an external class. The internal class of a member can unconditionally access all member attributes and member methods (including private and static members) of the external class ). In the internal class drawCircle method, you can easily access the radius of the Private member of the external class.

 

Note:

(1) When a Member's internal class has a member variable or method with the same name as the external class, it is hidden. That is, by default, members of the member's internal class are accessed.


  1. public class Circle {
  2. private double radius;
  3.  
  4. public Circle(double radius) {
  5. this.radius = radius;
  6. }
  7.  
  8. // Internal class
  9. class Draw {
  10. private double radius;
  11.  
  12. public Draw(double radius) {
  13. this.radius = radius;
  14. }
  15.  
  16. public void drawCircle() {
  17. // When the member's internal class has a member variable or method with the same name as the external class, the member's internal class is accessed by default.
  18. System.out.println("Circle---->" + radius);
  19. }
  20. }
  21.  
  22. public Draw getDrawInstance(double radius) {
  23. return new Draw(radius);
  24. }
  25.  
  26. public static void main(String[] args) {
  27. Circle circle = new Circle(12.5);
  28. circle.getDrawInstance(11.6).drawCircle(); // 11.6
  29. }
  30. }

To access members with the same name as an external class, you need to access the external class in the following form:

External class. this. member variable

 

  • External class. this. Member Method


    (2) The internal class of the member can access the members of the External class unconditionally, but the access to members of the internal class of the member is so simple. To access members of a Member's internal class in an external class, you must first create an object of the member's internal class and then access it by referencing the object:

    
      

    (3) The internal class of a member is attached to an external class. That is to say, to create an object of the internal class of a member, the premise is that an object of the external class must exist. The general method for creating class objects within a Member is as follows:

     

    
      

    2nd methods:

    
      

    (4) Internal classes can have private, protected, public, and package access permissions. For example, in the above example, if the Inner class of the member is modified in private mode, only internal access to the outer class is allowed. If the Inner class is modified in public mode, access is allowed anywhere. If the Inner class is modified in protected mode, access can only be performed under the same package or inherit from external classes. If it is the default access permission, access can only be performed under the same package. This is a little different from the external class. The external class can only be modified by the public and package access permissions.

    2. Local internal class

    A local internal class is a class defined in a method or a scope. The difference between a local internal class and a member's internal class is that access to the local internal class is limited to the method or the scope.

    Note:

    A local internal class is like a local variable in a method. It cannot have public, protected, private, or static modifiers.

    3. Anonymous internal class

    Anonymous classes cannot be referenced because they cannot have names. They must be declared as part of the new statement at creation. This requires another form of new statement, as shown below: new <class or interface> <class subject> in this form of new statement declares a new anonymous class, it extends a given class or implements a given interface. It also creates a new instance of that class and returns it as the result of the statement.

    For example, assume that you have a Map. The key is an item, and the value is the corresponding price. The unit is RMB. Now there is a need to convert the prices in it into US dollars. The traditional approach is to traverse the entire Map, then update each value, and convert the price to US dollars. This method is more troublesome. Function can be used to solve this problem.

    
      

    New Function () {...} Is to create an internal class.

     

    An anonymous internal class is the only class without a constructor (the constructor cannot be defined ). Because there is no constructor, the use of anonymous internal classes is very limited. Most anonymous internal classes are used for interface callback. During compilation, the anonymous internal class is automatically named Outter $1. class by the system. Generally, an anonymous internal class is used to inherit other classes or implement interfaces. No additional methods are required, but the inherited methods are overwritten or the interface methods are implemented.

    An anonymous internal class cannot be an abstract class, because the system immediately creates an internal class object when creating an anonymous internal class. Therefore, anonymous internal classes cannot be defined as abstract classes.

    4. static internal class

    Static internal classes are also defined in another class, except that a keyword static is added before the class. Static internal classes do not need to depend on external classes. This is similar to static member attributes of the class, and they cannot use non-static member variables or methods of external classes, because you can create static internal class objects without external class objects, conflicts may occur if you allow access to non-static members of the external class, because non-static members of external classes must be attached to specific objects.

    
      
    1. public class Outer2 {
    2.  
    3. private static String sname = "Outer2";
    4. private String name;
    5.  
    6. public Outer2(String name) {
    7. this.name = name;
    8. }
    9.  
    10. // Member internal class
    11. public static class Inner {
    12. public void print() {
    13. // The static internal class cannot access non-static member variables or methods of the external class
    14. // System.out.println("Outer---->" + name);
    15. // You can use static variables or methods.
    16. System.out.println("Outer---->" + sname);
    17. }
    18. }
    19. }

    Call:

    
      
    1. Outer2.Inner inner2 = new Outer2.Inner();
    2. inner2.print();
     

     

     

     

     

      1. public void drawCircle() {
      2. System.out.println("Circle---->" + Circle.this.radius); // 12.5
      3. }
      1. public class Circle {
      2. private double radius;
      3.  
      4. public Circle(double radius) {
      5. this.radius = radius;
      6. // Create an object for the internal class of the member
      7. new Draw().drawCircle();
      8. }
      9.  
      10. // Member internal class
      11. class Draw {
      12. public void drawCircle() {
      13. System.out.println("Circle---->" + radius); // 12.5
      14. }
      15. }
      16.  
      17. public static void main(String[] args) {
      18. Circle circle = new Circle(12.5); // Circle---->12.5
      19. }
      20. }
      1. package com.qunar.fresh;
      2.  
      3. /**
      4. * Created by xiaosi on 16-3-29.
      5. */
      6. public class Outer {
      7. private String name;
      8.  
      9. public Outer(String name) {
      10. this.name = name;
      11. }
      12.  
      13. // Member internal class
      14. class Inner {
      15. public void print() {
      16. System.out.println("Outer---->" + name); // Outer---->OuterClass
      17. }
      18. }
      19.  
      20. public static void main(String[] args) {
      21. Outer outer = new Outer("OuterClass");
      22. Outer.Inner inner = outer.new Inner();
      23. inner.print();
      24. }
      25. }
      1. package com.qunar.fresh;
      2.  
      3. /**
      4. * Created by xiaosi on 16-3-29.
      5. */
      6. public class Outer {
      7. private String name;
      8. private Inner inner = null;
      9.  
      10. public Outer(String name) {
      11. this.name = name;
      12. }
      13.  
      14. public Inner getInstance() {
      15. if (inner == null) {
      16. return new Inner();
      17. }
      18. return inner;
      19. }
      20.  
      21. // Member internal class
      22. class Inner {
      23. public void print() {
      24. System.out.println("Outer---->" + name); // Outer---->OuterClass
      25. }
      26. }
      27.  
      28. public static void main(String[] args) {
      29. Outer outer = new Outer("OuterClass");
      30. Outer.Inner inner = outer.getInstance();
      31. inner.print();
      32. }
      33. }
      1. @Test
      2. public void test1(){
      3. Map map = Maps.newHashMap();
      4. map.put("apple",4.5);
      5. map.put("bear",6.3);
      6. // {bear=6.3, apple=4.5}
      7. System.out.println(map.toString());
      8.  
      9. Map newMap = Maps.transformValues(map, new Function () {
      10. double rate = 0.1544;
      11. @Override
      12. // Convert to USD
      13. public Double apply(Double input) {
      14. return rate * input;
      15. }
      16. });
      17.  
      18. // {bear=0.97272, apple=0.6948000000000001}
      19. System.out.println(newMap.toString());
      20. }

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.