Java learning notes-nested classes and java learning notes nesting

Source: Internet
Author: User
Tags print print

Java learning notes-nested classes and java learning notes nesting
Nested class

There are two types of Nested classes: static and non-static, which correspond to static Nested classes and internal classes respectively.

1 class OuterClass {2     ...3     static class StaticNestedClass {4         ...5     }6     class InnerClass {7         ...8     }9 }

 

The static nesting class can only access the static members of the external class, and the internal class can access any members of the external class; they can be declaredprivate,public,protected, Or package private.

  • Static nested class instantiation method: OuterClass. StaticNestedClass nestedObject = new OuterClass. StaticNestedClass ();
  • Internal class instantiation method: OuterClass. InnerClass innerObject = outerObject. new InnerClass (); that is, internal classes can be accessed through external class instances.

There are two special internal classes: Local internal classes and anonymous classes.

Local internal class
  • Local CLasses can be declared in any block of the class, such as a method, for, or if block.
  • A local internal class can access members of an external class. If a local internal class is declared in a static block, it can access static members of an external class. If it is declared in a non-static block, all members of the external class can be accessed;
  • The local internal class can access the local variable of the block, but the local variable must be declared as final. Improvements have been made in jdk8. the local variable can be declared as final or javastively final;
  • Other features are similar to common internal classes.

The difference between the partial tively final and final local variables is that the former can not explicitly declare the variable as final, as long as the variable is not modified throughout the process (the default condition of the compiler is final ). For more information about why the final variable must be referenced in a local internal class, see

Why is final referenced by parameters of anonymous internal classes in java? . It generally means that a local internal class references a local variable, which is actually a value reference (or a value copy ). It can be considered that preventing external code blocks from ending before internal class running ends, leading to local variable recycling and error.

Anonymous class

The anonymous class is similar to a local internal class, but it is not named and is declared and instantiated at the same time. As follows:

 1 HelloWorld frenchGreeting = new HelloWorld() { 2             String name = "tout le monde"; 3             public void greet() { 4                 greetSomeone("tout le monde"); 5             } 6             public void greetSomeone(String someone) { 7                 name = someone; 8                 System.out.println("Salut " + name); 9             }10         };

The anonymous internal class is applicable only once. Other features are the same as local internal classes.

When Lambda expressions use anonymous internal classes, class names are not required. For interfaces with only one method, using Lambda is obviously simpler and clearer than implementing anonymous classes. Define a LambdaTest interface, which contains only one opt method:
1 interface LambdaTest {2     int opt(int a , int b);3 }4 5 LambdaTest sumTest = (a,b) -> a+b;

The first line is the Lambda expression Declaration, where (a, B) is the method parameter, a + B is the method body, and-> indicates passing the parameter to the method body.

  • The method body of a Lambda expression can be an expression or a code block. If it is an expression, the Java runtime calculates the expression and returns the result. If it is a code block, you can add a return statement to return the result.
  • A Lambda expression is actually a method declaration. It can be considered that a Lambda expression isAnonymous Method.
  • Lambda expressions are similar to local internal classes and anonymous classes. They can access variables of external classes and external code blocks.There is no problem of overwriting variables. We can think that a new code block is not introduced and it is the same as a local variable in an external code block..
  • Because of the third clause, in the parameters of the expression,Variable names with the same scope as those of the same level cannot be declaredOtherwise, a duplicate definition exception occurs.
  • Lambda expressions are implemented in the form of anonymous internal classes. The external variables accessed by Lambda expressions must be final or javastively final.

Example:

1 public class Lambda {2 3 private int var = 100; 4 private String x = "hello"; 5 6 interface Cal {7 int op (int a, int B ); 8} 9 10 interface Print {11 void print (String msg); 12} 13 14 public int operator (int a, int B, Cal cal) {15 return cal. op (a, B); 16} 17 18 public void operator1 (String msg, Print print) {19 print. print (msg); 20} 21 22 public void operator2 (String x) {23 24 // x = ""; 25 26 Print print = (msg)-> {27 System. out. println ("Lambda external variables:"); 28 System. out. println (x); 29 System. out. println (msg); 30 System. out. println (Lambda. this. x); 31}; 32 33 print. print (x); 34} 35 36 public static void main (String [] args) {37 Cal add = (a, B)-> {return a + B ;}; 38 Cal mul = (a, B)-> a * B; 39 40 Lambda lambda = new Lambda (); 41 System. out. println ("2 + 3 =" + lambda. operator (2, 3, add); 42 System. out. println ("2*3 =" + lambda. operator (2, 3, mul); 43 44 lambda. var = 200; 45 Print print = (msg)-> {46 System. out. println (msg); 47 System. out. println (lambda. var); 48}; 49 lambda. operator1 ("Hello World", print); 50 51 lambda. operator2 ("Hello Lambda"); 52} 53 54}

Running result:

1 2 + 3 = 52 2*3 = 63 Hello World4 2005 Lambda external access variable: 6 Hello Lambda7 Hello Lambda8 hello

The operator2 method can be used to verify the last three items. If you cancel the comments of 24 rows, the exception "local variables referenced from a lambda expression must be final or partial tively final" will be reported in 28 rows.

Target Type)

The target type is the type expected to be called by the external class method. In the preceding example, the target method that the operator expects to call is Cal. Java judges the target type based on the context and context information of the Lambda expression and calls it.

Example:
 1 public class TargetType { 2      3     interface Cal{ 4         String op(); 5     } 6      7     interface Cal1{ 8         int op1(); 9     }10     11     interface Cal2{12         void op1();13     }14     15     public static String invoke(Cal cal) {16         return cal.op();17     }18     19     public static void invoke(Cal1 cal1) {20         cal1.op1();21     }22     23     public static void invoke(Cal2 cal2) {24         cal2.op1();25     }26 27     public static void main(String[] args) {28         invoke(() -> "done");29         invoke(() -> 100);30         invoke(() -> {return;});31     }32 }

Declare three interfaces (Cal Cal1 Cal2) with the same name, but their return values are different. Three invoke methods are declared to receive three classes respectively, that is, the expected target type is different. Then perform the test:

All three statements in the main method are compiled, and eclipse prompts 28 lines to call the invoke of the target type Cal, and 29 lines to call the invoke of the target type Cal1, the following code calls the invoke of the target type Cal2 in line 30. The target type is shown in:

(1) If you add another sentence such as invoke ()-> 100.0), the compiler will report an error, Type mismatch: cannot convert from double to String;

(2) If you change The return value of The Cal interface method to int, besides 28 rows, 29 rows also report The error: The method invoke (TargetType. cal) is ambiguous for the type TargetType, that is, the compiler cannot determine which target type to call.

The examples in the official website documents are Runnable and Callable. The principle is the same as follows:
1 public interface Runnable {2     void run();3 }4 5 public interface Callable<V> {6     V call();7 }

Method declaration:

1 void invoke(Runnable r) {2     r.run();3 }4 5 <T> T invoke(Callable<T> c) {6     return c.call();7 }

 

Determine the target type based on the context. Because there is a return value, the Callable invoke method is called:
1 String s = invoke(() -> "done");
Summary:
  • Differences between static Nested classes and internal classes
  • Two special internal classes: Local internal class and anonymous internal class;
  • Special Implementation of anonymous internal classes: Lambda expressions, which can be considered the implementation of anonymous methods;
  • Lambda expressions determine the target type based on the context.
Refer:
  • Nested Classes
  • Lambda Expressions
 

 

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.