Java Basics notes -8- interfaces, lambda expressions and inner classes

Java Basics notes -8- interfaces, lambda expressions and inner classes

Firstly, at the interface (interface) technology, which is mainly used to describe what type having a function, and does not give a specific implementation of each function. A class can implement (Implement) one or more interfaces, and the interface where needed, at any time an object that implements the appropriate interface. After understanding the interface, and then continue to introduce and expression, which is a simple method code block can indicate future point in time of the execution. Using lambda expressions, you can use the code represents the callback or variable behavior in a compact and concise manner.

Next, a discussion within category (inner class) mechanism. In theory, some complicated internal class, the class is defined within the interior of another class, wherein the method may comprise accessing domain their outer class. Internal class used to design technology is mainly based cooperate with a set of relationships.

10.1 Interface

In the Java programming language, the interface is not a class, but a set of requirements for the class description, these classes are defined unified format to follow interface description.

In the Java language, the interface has two meanings

  • First of all the service refers to a conceptual interface, refers to the external system provides all methods of the class can be accessed by external users form the interface class
  • The second is the real interface keyword defines an interface, also known interface type.

In object-oriented programming, a class must define what to do rather than how to do it is sometimes very useful. An example of this front: abstract method signature is defined as a method, but does not provide implementations. Subclasses must implement the abstract methods defined by the parent class of their own. Thus, the abstract method to specify a method of interface rather than implementation. Although abstract classes and methods are useful, but this concept can be further extended. In java, the keyword may be used to interface the class interface and implementation methods completely separated.

Use the keyword interface to define an interface. And Class Definition is similar interface, and the interface declaration into the interface body

E.g:

interface Printable {
    final int MAX=100;
    void add();
    float sum(float x,float y);
}

1. interface declaration

Interface contains the interface declaration and the interface body, and class difference is that the interface declaration uses the keyword interface to indicate that he is an interface.

2. Interface body

The interface comprises a constant declarations (no variables) and two abstract methods section.

Only abstract methods and common methods in the interface body. And the interface body access all the constants are necessarily public (omitted allowed public, final modifier), access to all the abstract methods are necessarily public (omitted allowed public, abstract modifier), for example:

interface Printable {
    public final int MAX=100;
    public abstract void add();
    public abstract float sum(float x,float y);
}

In JDK8 previous versions, the interface can contain abstract methods from JDK8 start, in order to improve reusability of code, it allows to define the default interface and static methods. The default way to declare a default keyword, with the default implementation, implementation class either directly access the default interface method, you can cover it, re-implement the method, such as the following example:

public interface MyIFC{
    default void method1(){
        System.out.println("default method1");//声明了一个默认方法
    }
    static void method2(){
        System.out.println("static method2");//声明了一个静态方法
    }
    void method3();//声明了一个抽象方法
}

The following class implements this interface above, a non-abstract class Tester class must implement the abstract the method3 () method MyIFC interface. Examples method1 tester can directly access the interface defined in () Default Method

public class Tester implements MyIFC{
    public void method3(){//实现接口中的method3()方法
        System.out.println("method3);
    }
    public static void main(String args[]){
        Tester t=new Tester();
        t.method1();//访问接口中的默认方法
        t.method2();//编译出错,Tester实例不能访问MyIFC接口的静态方法
        MyIFC.method2();//合法,可以通过接口的名字来访问它的静态方法
        t.method3();        
    }
}

Interface Static methods can only be accessed in the internal interfaces, or other programs to access its static method name of the interface, if you try to access the static instance of a class method by implementing the interface will cause compile errors, such as:

t.method2();//编译出错,Tester实例不能访问MyIFC接口的静态方法
MyIFC.method2();//合法,可以通过接口的名字来访问它的静态方法

Also, note that the default interface is to provide a method to achieve Although you can improve code reusability, but still be careful to use this feature. Because the hierarchy more complex software systems, this feature will make the program code causes the discrepancy and confusion.

Interface no construction method can not be instantiated. In the method defined in the interface configuration is illegal, for example:

public interface A {
    public A(){//编译出错,接口中不允许定义构造方法
        ...
    }
    void method();
}

Although not allowed to create an instance of the interface, but allows you to define an interface reference type variable that references an instance of this class implement an interface, such as:

//引用变量t被定义为Photographable接口类型,他引用Camera实例
Photographable t=new Camera();

2 implements the interface

In the Java language, interface consists of class to implement in order to use interface, a class can implement multiple interfaces, class by using the keyword implements declare themselves to achieve one or more interfaces. If you implement multiple interfaces, interface name separated by commas.

To make class implements an interface, usually requires the following two steps:

  • 1) to declare a class that implements the given interface.
  • 2) all interface methods defined.

  The A class implements interfaces Printable and Addable

class A implements Printable,Addable

  Animal e.g. another subclass of Dog and sleepable interfaces implemented Eatable

class Dog extends Animal implements Eatable,Sleepable

If a non-abstract class implements an interface, then this class all methods of the interface must be rewritten to note that, due to the methods in the interface must bepublic abstract方法 so non-abstract class when rewriting the interface method is not only to remove the abstract body modification methods are given, and the access method must be clear with the public to modify (or reduced access, which is not allowed) non-abstract class implements an interface method must be rewritten interface, and therefore also known as this class implements an interface method, Java interfaces are provided in the respective package, not only by the import statement included in the category can be introduced, it may also be introduced in the package interface, such as:

import java.io.*;

Interface methods overridden and the object class interface class constants can be directly invoked, and constants may be called directly by the interface name.

When the interface declaration, if the front plus public key interface, call it public interface that can be implemented in any class, if a public interfaces without modification, then call it a friendly interface class, with a friendly interface class can be the interface is implemented in the same package.

If the parent class implements an interface, then a subclass of naturally implements an interface, subclasses do not have to explicitly declare using the keyword implements implements this interface.

The interface can also be inherited, only one interface can be another sub-interface interface keyword extends statement. Because interface methods and constants are public, sub-interface inherits all the methods and constants parent interface.

Note: If you declare a class implement an interface, but did not rewrite all interface methods, then this class must be abstracts like this sentence means that when the class implements an interface, it all abstract methods in the interface must be implemented otherwise, the class must be defined as an abstract class.

E.g:

interface Computable{
    final int MAX=100;
    void speak();
    int f(int x);
    float g(float x,float y);
}
abstract class A implements Computable{
    public int f(int x){
        int sum=0;
        for(int i=1;i<=x;i++){
            sum=sum+I;
        }
    return sum
    }
}

3 understand Interface

Different classes can implement the same interface, the same class may also implement multiple interfaces.

When you do not want certain classes through inheritance so that they have some of the same methods, we can consider these classes to implement the same interface rather than their declared as a subclass of the same class.

Interface Example 4

4.1 Comparator Interface

We have learned how to sort an array of objects, provided that these objects are achieved instance of a class Comparable interface, for example, you can sort an array of strings, because the String class implements
Comparable<String>, and String.compareToways to compare strings lexicographically .

Now suppose we want to ascending order of length sorting strings, rather than sorted in lexical order. Certainly can not let the String class implements compareTo method in two different ways --- What's more, String class nor should we be modified.

To handle this situation, there is a method Arrays.sort second version, there is an array and a comparator (Comparator) is an example achieved Comparator interface class as a parameter comparator.

public interface Comparators {
    int compare(T first, T second);
}

Yaoan comparison string length, can be defined as an implementation Comparator<String>class:

class LengthComparator implements Comparator<String> {
    public int compare(String first, String second) {
    return first.length() - second.length();
    }
}

Specifically completes the comparison, we need to create an instance:

Comparator<String> comp = new LengthComparator();
if (comp.compare(words[i], words[j]) > 0)...

This will invoke words [i] .compareTo (words [j]) for comparison. Compare this method to call on the comparison object, instead of calling on the string itself.

NOTE: Although LengthComparator object does not state, but still need to create an instance of the object. We need to compare this example to call the method --- it is not a static method.

To sort an array, you need to pass a LengthComparator object Arrays.sort method:

String[] friends = { "Peter", "Paul", "Mary" };
Arrays,sort(friends, new LengthComparator()):

Now this may be an array [ "Paul", "Mary", "Peter"] or [ "Mary", "Paul", "Peter"].

Later we will realize that the use of a lambda expression makes it easier to use Comparator.

4.2 Callback Interface

Callback (callback) is a common programming model. In this mode, you can indicate when a specific event occurs action should be taken. For example, you can indicate when you press the mouse to select a menu item or what action should be taken. However, since so far has not describe how to implement the user interface, we can only discuss some of the above-mentioned operation is similar, but the relatively simple case.

And classes, Java interface is also an important one data type, interface declaration of a variable called interface variables. Interfaces belonging to a reference type variable, the interface can be stored in the variable reference to an instance of the class implement the interface, i.e., storing a reference to the object

If, assuming Com is an interface, then you can declare a variable with Com:

Com com;

As shown in FIG memory model, in this case an empty interface com, com because variables are not stored instance of a class that interface references.

Com assume ImpleCom class is the interface to create a name for the target object with ImpleCom, then the object is not only an object class can call ImpleCom any original method, interface method implemented by this class can also call.

ImpleCom object=new ImpleCom();

In Java, the interface callback means can achieve the object of a certain type of class interface to create a reference to the assigned interface variables declared in that interface, then the interface variables you can call interface methods are classes. In fact, when the interface class variable call interface methods are implemented, it is to tell the corresponding object calling this method.

The interface is very similar to the callback we call the subclass overrides the method introduced before uploading type objects

4.2.1 Using the interface reference

You can use the interface might be surprised to create a reference variable, you can create an interface reference variables, such variables can be referenced to achieve any of his object interface when calling a method on an object through the interface, the object will be executed once implemented that approach on the version, the process is similar to using a reference to the parent class to access the subclass object.

4.2.2 Interface can be extended

Use the keyword extends, an interface can inherit another interface. As expansion interface of syntax and grammar class inheritance, all methods inherited when a class implements an interface to other interfaces, he must be defined in the interface inheritance chain to provide implementations.

Example code:

interface A {
    void meth1();
    void meth2();
}
interface B extends A {
    void meth3();
}
class MyClass implements B {
    public void meth1(){
        System.out.println("Implement meth1().");
    }
    public void meth2() {
        System.out.println("Implement meth2().");
    }
    public void meth3() {
        System.out.println("Implement meth3().");
    }
class IFExtends {
    public static void main(String args[]){
        MyClass ob=new MyClass();

        ob.meth1();
        ob.meth2();
        ob.meth3();
        }
    }
}

Callback Interface 4.2.3 Example 1

Callback (callback) is a common programming model. In this mode, you can indicate when a specific event occurs action should be taken. For example, you can indicate when you press the mouse to select a menu item or what action should be taken. However, since so far has not describe how to implement the user interface, we can only discuss some of the above-mentioned operation is similar, but the relatively simple case.

There is a Timer class in java.swing package, it can use a notice on the arrival of a given time interval. For example, if there is a program clock, every second can be obtained a notification request to update the clock dial. When the timer is configured, a required set time interval, the timer and Advertisement, when arrival time what action needs to be done.

How to tell the timer what to do it? In many programming languages, you can provide a function name, timers call it periodically. However, the standard Java class library is used in the object-oriented method. It will target a class passed to the timer, then the timer calls the method of the object. Since the object can carry some additional information, pass an object than a transfer function much more flexible.

Of course, the timer needs to know which method call and ask the class object passed belongs to achieve the ActionListener interface java.awt.event package. Here is this interface:

public interface ActionListener {
    void actionPerformed(ActionEvent event);
}

When you reach the specified time interval, the timer calls the actionPerformed method.

Suppose you want to print a message every 10 seconds "At the tone, the time is ...", and then ring out, then it should define a class that implements the ActionListener interface, then the statement to be executed in the actionPerformed method.

class TimePrinter implements ActionListener {
    public void actionPerformed(ActionEvent event) {
        System.out.println("At the tone, the time is " + new Date());
        Toolkit.getDefaultToolkit().beep();
    }
}

Note actionPerformed ActionEvent parameter method. This parameter provides information about the event, for example, produce a source object of this event. For more information on this area, see Chapter 8. In this program, detailed information about the event is not important, so you can safely ignore this parameter.

Next, the configuration of this class of an object, and pass it to the Timer constructor.

ActionListener listener = new TimePrinter();
Timer t = new Timer(10000, listener) ;

The first parameter is sent Timer constructor advertisement interval, it milliseconds. Here we hope once every 10 seconds notice. The second parameter is the listener object.

Finally, start the timer:

t.start();

Every 10 seconds, the following information is displayed once, and then beep bell.

At the tone, the time is Wed Apr 13 23:29:08 PDT 2016

Listing 6-3 shows the operating behavior timers and listeners. After the timer is started, the program will pop up a message box and wait for the user clicks the Ok button to terminate the program execution. While the program waits for a user operation, a display every 10 seconds of the current time.

To have some patience to run this program. After the program starts, it will immediately displays a "Quit program?" The words of the dialog box, after 10 seconds, Section 1 timer message will be displayed.

Note that this program in addition to import javax.swing. * And java.util. *, But also introduced javax.swing.Timer by class name. This eliminates the ambiguity and generate between javax.swing.Timer of java.util.Timer. java.util.Timer here is a class independent embodiment of the present, it is mainly used for scheduling background tasks.

Callback Interface 4.2.4 Example 2

Example: The boss assigned to staff work, employees need to get things done after the reply to the boss, the boss react to.

The above is a more classic example, the following code is used to achieve the above example:

  • 1 to define an interface
package JieKouHuiDiao;
//定义一个接口
public interface JieKou {
    public void show();
}
  • 2 define a class that implements the interface Boss
package JieKouHuiDiao;
public class Boss implements JieKou {
//定义一个老板实现接口
    @Override
    public void show() {
        System.out.println("知道了");
    } 
}
  • 3 defines a class of employees Employee
package JieKouHuiDiao;
public class Employee {
    //接口属性,方便后边注册
    JieKou jiekou;
    //注册一个接口属性,等需要调用的时候传入一个接口类型的参数,即本例中的Boss和Employee,
    public Employee zhuce(JieKou jiekou,Employee e){
        this.jiekou=jiekou;
        return e;
    }
    public void dosomething(){
        System.out.println("拼命做事,做完告诉老板");
        //接口回调,如果没有注册调用,接口中的抽象方法也不会影响dosomething
        jiekou.show();
    }
}
  • 4 test class
package JieKouHuiDiao;
public class Test {
    public static void main(String[] args) {
        Employee e=new Employee();
        //需要调用的时候先注册,传入Boss类型对象和员工参数
        Employee e1=e.zhuce(new Boss(),e);
        e1.dosomething();
    }
}

Through the above examples and code should have a more basic understanding of the interface as well as the use of anonymous inner callback classes to implement


5 interfaces with the Polymorphism

Generated by the interface Polymorphism refers to different classes in the same time achieve an interface may have different implementations, the interface variables may have multiple forms at the interface a callback method.

interface ComputerAverage {
    public double average(double a,double b);
}

class A implements ComputerAverage{
    public double average(double a,double b){
        double aver=0;
        aver=(a+b)/2;
        return aver;
    }
}

class Bi implements ComputerAverage{
    public double arerage(double a,double b){
        double aver=Math.sqrt(a*b);
        return aver;
    }
}

public class exercise{
    public static void main(String args[]){
        ComputerAverage computer;
        double a=11.23;
        double b=22.78;
        computer=new A();
        double result=computer.average(a,b);//算术平均数
        computer=new A();
        double result=computer.average(a,b);//几何平均数
    }
}

6 interface variables as arguments

7 abstract class interface

You may have a question: Why Java programming language but also worked tirelessly to introduce the concept of interfaces? Why not directly designed abstract class Comparable shown below.

abstract class Comparable // why not?
{
    public abstract int compareTo(Object other);
}

Then, the Employee class directly again extend this abstract class, and provide an implementation compareTo method:

class Employee extends Comparable // why not?
{
    public int compareTo(Object other) { . . . }
}

Unfortunately, the use of abstract classes indicates that there is a problem common attribute: Each class can only extend to a class. Suppose Employee class has been expanded to a class, the Person e.g., so it can not extend the second category like this:

class Employee extends Person, Comparable // Error

But each class can implement multiple interfaces such as the following:

class Employee extends Person implements Comparable // OK

Some programming languages ​​allow a class has multiple superclasses, such as C ++. We refer to this feature is called multiple inheritance (multiple inheritance). The designers of Java chose not to support multiple inheritance, multiple inheritance is mainly due to the language itself will become very complicated (like C ++), efficiency will be reduced (as in Eiffel).

In fact, the interface can provide most of the benefits of multiple inheritance, multiple inheritance while avoiding the complexity and inefficiency

Compare 7.1 abstract classes and interfaces

Comparison of abstract classes and interfaces are as follows:

1.abstract abstract class and interface has a method

2. The interface can only constants, can not have variable; abstract classes and both have constant and can have a variable

3.abstract class may also be non-abstract methods, interfaces may not

In the design process, should be determined using specific analysis method is an abstract class or interface. In addition to providing important abstract class requires subclasses abstract method overridden, but also provides a subclass needs to inherit variables and non-abstract way, if subclasses need to override the abstract methods of the parent class, you also need some variables inherited from the parent class or inherited some of the important non-abstract method, you can consider using abstract.

If you do not need to inherit a problem, just need several classes given some important implementation details of the abstract method, you can consider using the interface.

10.2 lambda expression

Now you can learn the lambda expression, which is the Java language these years, a change most people excited. You will learn how to use a lambda expression uses a simple syntax for defining a block of code, and how to write code lambda expression.

1 Before learning lambda expression: Some simple examples

1.1 Lambda expression syntax

The basic syntax:

(parameters) -> expression

or

(parameters) ->{ statements; }

Here is a simple example of Java lambda expression:

// 1. 不需要参数,返回值为 5  
() -> 5  
// 2. 接收一个参数(数字类型),返回其2倍的值  
x -> 2 * x  
// 3. 接受2个参数(数字),并返回他们的差值  
(x, y) -> x – y  
// 4. 接收2个int型整数,返回他们的和  
(int x, int y) -> x + y  
// 5. 接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void)  
(String s) -> System.out.print(s)  

More to the chain: https: //www.cnblogs.com/franson-2016/p/5593080.html

2 Why is the introduction of a lambda expression

a lambda expression is a code block can be transmitted, can be performed once or several times later. Before specific description grammar (and explain this curious name), the following step back, look at what we place in Java used this code block.

We have learned how to work a specified time interval to complete. This will work on a ActionListener actionPerformed method of:

class Worker implements ActionListener {
    public void actionPerformed(ActionEvent event) {
        // do some work
    }
}

When you want to repeatedly execute this code, you can construct an instance of the Worker class. Then this instance to submit a Timer object. The focus here is the code after actionPerformed method contains want to perform.

Or consider how to use a custom comparator to complete the order. If you want to length rather than the default dictionary order sort strings may be passed to a sort method Comparator object:

class LengthComparator implements Comparator<String> {
    public int compare(String first, String second) {
        return first.length() - second.length();
    }
}
...
Arrays.sort(strings, new LengthComparator()) ;

compare method is not called immediately. In fact, before the completion of sorting an array, sort method will always be invoked compare methods, as long as the order of the elements is incorrect will rearrange the elements. Comparison of the required elements of the code segment in sort method, this code will be integrated with the rest of the sorting logic (you probably do not intend to re-implement the remaining part of this logic)

These two examples have something in common, it is to pass a code block to an object (a timer, or a sort method). This block of code will call at some future time.

So far, a transfer in Java code segment is not easy, can not directly pass code segment, Java is an object-oriented language, it is necessary to construct an object of this object's class needs to have a way to include the necessary code.

In other languages, code blocks can be processed directly. Java has long been a designer refused to increase this feature. After all, Java is a powerful place lies in its simplicity and consistency. If you only want a simple little feature can make the code number, put this feature added to the language, this language will soon become a mess, you can not be managed. However, in another of those languages, not just create threads or register button click event handler easier; most of their API is simpler, more consistent and more powerful. In Java, you can also write a similar class objects using the API specific function, but this can be inconvenient to use API.

For now, the question is not whether the enhanced Java support functional programming, but how to do it. Designers try to do for many years, finally finding a suitable Java design. The next section, you'll learn how to deal with Java SE8 code block.

3 lambda expression syntax

Consider again the example of the sort discussed one. We pass code to check whether a string is shorter than another string. To calculate here:

first.length() - second.length()

What first and second that? They are strings. Java is a strongly typed language, so we have to specify their type:

(String first, String second)
    -> first.length() - second.length()

This is the first expression you see. lambda expression is a block of code, and the code must pass a variable specification.

Why does this name? Many years ago, when no computer, logician Alonzo Church wants to formally represent mathematical functions can be effectively calculated. (Curiously, some functions have been known to be present, but no one knows how to calculate the value of these functions.) He used the Greek letter lambda (λ) to mark parameters if he knows Java API, it might be written as

λfirst.λsecond.first.length() - second.length()

You've seen one kind of lambda expression in the form of Java: Parameter arrow (->), and an expression. If the code can not be completed in a calculated expression, you can write the same way as like, put this code in parentheses, and contains explicit return statement. E.g:

(String first, String second) -> {
        if (first.length() < second.length()) return -1;
        else if (first.length() > second.length()) return 1;
        else return 0;
    }

Even if there is no parameter lambda expression, still provide empty parentheses, like non-parametric methods, like:

0 -> { for (int i = 100; i >= 0;i ) System.out.println(i); }

If the type can be deduced from a lambda expression parameter, its type can be ignored. E.g:

Comparator<String> comp
    = (first, second) // Same as (String first, String second)
        -> first.length() - second.length();

Here, the compiler can deduce the first and second string must be, because the lambda expression is assigned to a string comparator. (The next section will analyze the assignment in more detail.)

If the method is only one parameter, and this type of argument can be deduced, you can even omit parentheses:

ActionListener listener = event ->
    System.out.println("The time is " + new Date()");
    // Instead of (event) -> . . . or (ActionEvent event) -> . . .

Without specifying the return type of the lambda expression. The return type of the lambda expression will always be derived from the context derivation. For example, the following expression

(String first, String second) -> first.length() - second.length()

May be used in a context where the results of type int.

Note: If a lambda expression that returns a value only in certain branches, but does not return a value in some other branch, which is illegal. For example, (int x)-> { if (x >= 0) return 1; }not legal.

Listing 6-6 shows how to use the program in a lambda expression comparator and an action listener.

程序清单6-6 lambda/LambdaTest.java
package lambda;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
/**
* This program demonstrates the use of lambda expressions.
* ©version 1.0 2015-05-12
* ©author Cay Horstmann
*/
public class LambdaTest {
    public static void main(String[] args) {
        String[] planets = new String[] { "Mercury" , "Venus", "Earth" , "Mars" , "Jupiter" , "Saturn", "Uranus", "Neptune" };
        System.out.println(Arrays.toString(planets));
        System.out.println("Sorted in dictionary order:") ;
        Arrays.sort(planets) ;
        System.out.println (Arrays.toString(planets)) ;
        System.out.println ("Sorted by length:");
        Arrays.sort(planets, (first , second) -> first .length() - second .length()) ;
        System.out.println(Arrays.toString(planets)) ;
        Timer t = new Timer(1000, event ->
            System.out.println ("The time is " + new Date())) ;
        t.start() ;
        // keep program running until user selects "0k"
        JOptionPane.showMessageDialog (nul1 , "Quit program?");
        System.exit (O) ;
    }
}

4 Functional Interface

As already discussed, Java interface package has had a lot of code blocks, such as ActionListener or Comparator, lambda expressions these interfaces are compatible,

For only one interface abstract method, when in need of such interfaces can provide a lambda expression. This interface is called interface function (functional interface).

You may wonder why functional interface must have an abstract method. Not all methods are abstract interfaces do? In fact, the interface is entirely possible to re-declare the method of the Object class, such as toString or clone, these statements may make the method is no longer abstract. (Some interfaces will re-declare Object methods in the Java API for additional javadoc comments Comparator AP Shu is one such example.) More importantly, in JavaSE 8, the interface can be non-abstract method declaration.

To show how to convert a function interface, considered below Arrays.sort method. It's the second argument requires a Comparator instance, Comparator is only one way interface, it is possible to provide a lambda expression:

Arrays.sort (words ,
    (first , second) -> first.length() - second.length()) ;

At the bottom, Arrays.sort method receives achieved Comparator The objects of a class. Compare method call on this object will execute the body of the lambda expression. These objects and classes management depends entirely on the specific implementation, as compared with conventional inline type, which may be much more efficient. Preferably the lambda expression can be seen as a function, rather than an object, receiving the lambda expression can be further passed to the function interface

lambda expression can be converted to the interface, and this gives a lambda expression is very attractive. Specific syntax is very short. Next, look at an example:

Timer t = new Timer(1000, event ->
    {
        System.out.println("At the tone, the time is " + new DateO);
        Toolkit.getDefaultToolkit().beep();
    });

Compared with the use of a class that implements the ActionListener interface, this is much better code readability. In fact, in Java, for lambda expressions we can do can only be converted to a function interface. In other support
hold function literal programming language, you can declare the function type (such as (String, String) -> int ), declare these types of variables, you can also use a variable holds a function expression. However, Java designers decided to keep our familiar interface concept, has not increased as a function of the type of the Java language.

lambda expressions to be continued

10.3 inner class

Examples of simple inner class

As already know, there are two important categories of members: members of variables and methods, in fact, Java also allows classes can have another member: internal class.

Java supports the statement of another class in a class, this class is called inner classes. And comprising inner class class is called class fitted within the class. Class member variables fitted inner classes are still valid within the class, the method inside the class methods fitted class can be called.

Class body not declare class variables and class methods internal class, class body may be fitted with a class object is an internal class declaration, as a member of the class fitted.

Its interior is fitted only class class uses other classes can not be used inside the class declaration of a class of objects. In addition, since the class member variables fitted inside the class are still valid within the class, inner classes and make the interaction fitted classes more convenient.

For example, some kind of farm breeds a special kind of cattle, but do not want other farm breeding this particular species of cattle, then this type of farm you can create a special category that total cattle as their own internal class.

class RedCowFrom{
    String fromName;
    RedCow cow;
    RedCowFrom(){
    }
    RedCowFrom(String s){
        cow=new RedCow(150,112,5000);
        fromName=s;
    }
    public void showCowMess(){
        cow.speak();
    }
    class RedCow{
        String cowName="hongniu";
        int height,weight,price;
        RedCow(int h,int w,int p){
            heigh=h;
            weight=w;
            price=p;
        }
        void speak() {
            System.out.println(cowName+"height is:"+height+"height is:"+height+"price is:"+price);
        }
    }
}
public class exercise{
    public static void main(String args[]){
        RedCowFrom from=new RedCowFrom("cow1");
        from.showCowMess();
    }
}

Internal class (inner class) is defined in another class class. Why do I need to use it inside the class? The main reasons are the following three points:

  • Method within the class can access the data where the scope of the definition of the class, including private data.
  • Class can be hidden to other classes of the same package.

To define when a callback function and do not want to write a lot of code, use the anonymous (anonymous) inner classes more convenient. We will compare this complex content in several parts introduced.

  • In Section 6.4.1, we are given a simple internal type, it accesses the instance field enclosing class.
  • In Section 6.4.2, given the special syntax rules inside the class.
  • In section 6.4.3, a taste of what's inside the inner class, explore how to convert it into a regular class. Squeamish readers can skip this section.
  • In Section 6.4.4, we discuss the local internal class, it can access the local variables of the enclosing scope.
  • In section 6.4.5, we introduce anonymous inner classes, indicating a basic method for implementing the callback before lambda expressions in Java.
  • Finally, in Section 6.4.6, we describe how nested static inner classes in secondary classes.

C ++ comments:

Nested C ++ classes. Class contains a nested class role in the peripheral region. The following is a typical example, a class definition list class and a class defined iterator position of a storage node.

class LinkedList {
public:
  class Iterator // a nested class
  {
      public: void;
      insert(int x);
      int erase();
      ...
  };
private:
  class Link // a nested class
  {
      public:
          Link* next;
          int data;
  };
    ...
};

The nested relationship between a class, rather than the relationship between objects. LinkedList object does not contain a sub-object type or Iterator Link type.

Nested class has two benefits: Naming control and access control. As the name Iterator is nested inside the LinkedList class, so the outside is named LinkedList :: Iterator, so it will not conflict with other classes of named Iterator. This is not important in Java, because Java package already provides the same naming control. Note that, the private portion located LinkedList class Link class, therefore, are not visible to other Link code. In view of this situation, the data field design Link can be in the public domain, and it is still safe. These data fields may only be LinkedList class (having access to the data fields reasonably required) Access Method and not exposed to other code. In Java, inner classes can only achieve such control.

However, Java inner classes has another function, which makes it more abundant than C ++ nested class, more versatile. Inside the object class has an implicit reference, it refers to a peripheral object instance of the class internal object. With this pointer, the entire state of the peripheral access to the class object. Later in the chapter, we will see more information about this mechanism of Java

In Java, the class is not such an additional static internal pointers, such an internal class in C ++ nested class is very similar.

Guess you like

Origin www.cnblogs.com/whatsabc/p/11520897.html