Chapter VI interfaces, lambda expressions and inner classes | Study Notes

Java core technology Volume

6.1 Interface

  • Interface concept

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.

例如:
    public interface Comparable
    {
        int compareTo(Object other);
    }

Comparable any class that implements an interface to the compareTo method comprising, and the parameters of this method must be an Object object and returns an array of integers.
Interface methods automatically belong to public. Therefore, when declared in the interface method, do not provide keyword public.
To make class implements an interface, you need the following two steps:
1. declare the class that implements the given interface.
2. Interface methods are defined.

例如:
    public int compareTo(Object otherObject)
    {
        Employee other = (Employee) otherObject;
        return Double ,compare(sal ary, other,sal ary);
    }
  • Characteristics of the interface

The interface is not a class, in particular, can not be used to instantiate new operator interface, however, the object can not be constructed despite the interface, the interface able to declare variables.

Comparable x; // OK

Interface variable must reference a class that implements the object interface:

x = new Employee(. . .); // OK provided Employee implements Comparable

Interface can also expand:

例如:假设有一个称为Moveable的接口
    public interface Moveable
    {
        void move(double x, double y);
    }
然而,可以以它为基础拓展一个叫做Powered的接口:
    public interface Powered extends Moveable
    {
        double milesPerCallon();
    }
虽然在接口中不能包含实例域或静态方法,但却可以包含常量。
    public interface Powered extends Moveable
    {
        double milesPerCallon();
        double SPEED. LIHIT = 95; // a public static final constant
    }

And interface methods are automatically set as public, the interface area is automatically set to public static final.

  • Interfaces and abstract classes
  • Static method

So far, the usual practice to fight the house accompanied by static methods class.

例如:
    public interface Path//Path.get("jdk1.8.0", "jre", "bin")
    {
        public static Path get(String first, String... more) {
            return Fi1eSystems.getDefault().getPath(first, more);
        }
        ...
    }
  • The default method

It can provide a default implementation for the interface method. You must use the default modifier.

例如:
    public interface Comparable<T>
    {
        default int compareTo(T other) { return 0; }
        // B y default, all elements are the same
    }

Sometimes the default method is useful. For example, if you want to be notified when a mouse click occurs time, we must realize that contains five interfaces:

  public interface MouseListener
    {
        void mousedieked(MouseEvent event);
        void mousePressed(MouseEvent event);
        void mouseReleased(MouseEvent event);
        void mouseEntered(MouseEvent event);
        void mouseExited(MouseEvent event);
    }
    可以把所有方法声明为默认方法,这些默认方法什么也不做:
    public interface MouseListener
    {
        default void mousedieked(MouseEvent event) {}
        default void mousePressed(MouseEvent event) {}
        default void mouseReleased(MouseEvent event) {}
        default void mouseEntered(MouseEvent event) {}
        default void mouseExited(MouseEvent event) {}
    }

The default method can call any other method.

例如,Collection接口可以定义一个便利方法:
    public interface Collection
    {
        int size(); // An abstract method
        default boolean isEmpty()
        {
            return size() == 0;
        } 
        ...
    }

To achieve this Collection isEmpty programmers do not have to worry about the realization of the method.

  • The default method to resolve conflict

Rules:
1. superclass priority. If the super class provides a specific method of the same name and have the same type parameter to return the default method is ignored.
2. Interface conflict. If a super-interface provides a default method, another interface provides a parameterized type of the same name and the same method, you must override this method to resolve the conflict.

6.2 Interface Example

  • Interface and callback

Callback is a common programming model. In mode, you can point out the action when a specific event occurs that should be taken.

  • Comparator interface
  • Object cloning

Cloneable interface provides a safe method to clone.
Here Insert Picture Description
For each class, is determined:
1. The default clone method meets the requirements;
2. call clone on whether variable subobject default clone repair method;
3. Whether using the clone should
actually third option is the default option. If the selected item 1 or 2, class must:
1. implement Cloneable interface;
2 clone redefined method and specify access modifier public.

6.3 lambda expressions

  • Why the introduction of lambda expressions

a code block can be transmitted when the lambda expression can be performed after one or more times.
ActionPerformed method to understand how work gets done at specified intervals, will this work in a ActionListener in:

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

When the desired song is repeatedly executed and the code phase, can be configured to a Worker class instance. Then this example submitted to a Timer object.
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.lengthQ - second.length();
        }
    }
    . .
    Arrays.sort(strings, new LengthComparator());

compare not called immediately. In fact, before the completion of sorting an array, sort method will always be invoked compare methods, as long as the elements in the incorrect order will rearrange the elements.

  • lambda expressions to grammar
例如:
    (String first, String second)
        -> first.length() - second.length()

lambda expression is a block of code, and the code must be passed in a variable specification.

(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, as the same method with no parameters:

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

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

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

BiFunction<String, String, Integer> comp
    = (first, second) -> first.length() - second.length();
  • Method references

For example, suppose you want to appear a long time to print this timer event object, you can call:

Timer t = new Timer(1000, event -> System.out.println(event)):

The print method Timer passed to the constructor better.

Timer t = new Timer(1000, Systey.out::println);

Expressions Systey.out :: println is a method reference. Is equivalent to a lambda expression x> System.out.println (x)
is assumed to want to sort strings, regardless of the letter case.

  Arrays.sort(strings,String::conpareToIgnoreCase)

:: operator using the partition method name or an object class name. There are three cases:

•object::instanceMethod
•Class::staticMethod
•Class::instanceMethod

This parameter can be used in the method of reference. For example, this :: equals equal to x -> this.equals (x).
Use super is legal: super :: instanceMethod

例如:
    class Greeter
    {
        public void greet()
        {
            System.out.println("Hello, world!");
        }
        }
     class TimedCreeter extends Greeter
        {
            public void greet()
        {
        Timer t = new Timer(1000, super::greet);
        t.start();
        }
    }
  • Constructor references

The constructor is very similar to the reference method, but a method called new. For example, Person :: new constructor is a Person of reference.
Suppose you have a list of strings, you can convert it to a Person array of objects, for which the constructor to be invoked on each string, call as follows:

  ArrayList<String> names = . . .;
        Stream<Person> stream = names.stream().map(Person::new);
        List<Person> people = stream.collect(Collectors.toList());

You can create an array reference constructor type. E.g., int [] :: new constructor is a reference, it has one parameter: the length of the array. This is equivalent to a lambda expression x -> new int [x] .
Java has a limit, you can not build an array of generic type T.

  • Variable Scope

lambda expression consists of three parts:
1. a code block;
2. parameter;
3. the values of the free variables, which refers to non-parametric variables and not defined in the code.

  • Deal with lambda expressions

Focus on the use of lambda expressions is to delay execution. If you want to immediately execute the code, it can be executed directly, without the need to wrap it in a lambda expression.
Reasons:
1. Allow a separate thread in the code;
2. Run the code multiple times;
3. allow code in place of the algorithm;
4. occurrence of a situation code execution;
5. refers only necessary to run the code.
Suppose you want to repeat an action n times. This action will be transmitted with a repetition times and repeat method:

repeat(10, () -> System.out.println("Hello, World!"));

Here Insert Picture Description
Here Insert Picture Description

6.4 Internal class

In another class category is defined by the internal class.
Use reasons:
1. The data access method within the class of class was defined scope, including proprietary data.
2. The inner class can be hidden to other classes of the same package.
3. When you want to define a callback function and do not want to write a lot of code, using anonymous inner classes more convenient.
The nested relationship between a class, rather than by the relationship between the objects. Nested class has two benefits: Naming control and access control.

  • Internal class used to access the object state

In TimerTest example, and a TalkingClock abstract class. Parameters need to provide two clock configuration of a speech: release switch flag advertisement spacing and ringtones.

  public class TalkingClock
    {
        private int interval:
        private boolean beep;
        
        public TalkingClock(int interval, boolean beep) { . . . }
        public void start() { . . . }
        
        public class TimePrinter implements ActionListener
        // an inner class
        {
            ...
        }
    }

It is noted here TimePrinter TalkingClock positioned within the class category.
actionPerformed method checks the flag before the beep tones occur.

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

TimePrinter class has no instance field or variable named beep, and replaced by a beep quoted domain creation TalkingClock objects TimePrinter's.
Here Insert Picture Description

Special syntax rules inside the class
enclosing class references formal grammar: OuterClass.this

例如:
    public void actionPerformed(ActionEvent event)
    {
            ...
        if (TalkingClock.this.beep) Toolkit.getDefaultToolkitO.beep();
    }
    采用下列语法格式更明确地编写内部对象的构造器:
        outerObject.new InnerClass(construction parameters)
    例如:
        ActionListener listener = this.new TimerPrinter();
    TalkingClock jabberer = new TalkingClock(1000, true);
    TalkingOock.TiiePrinter listener= jabberer.newTimePrinter();

内部类中声明的所有静态域都必须是final。
内部类不能用static方法。

  • 内部类是否有用、必要和安全
  • 局部内部类
  • 由外部方法访问变量

局部类不仅能够访问包含他们的内部类,还可以访问局部变量。

例如:将TalkingClock 构造器的参数 interval和 beep 移至 start方法中。
    public void start(int interval, boolean beep)
    {
        class TimePrinter implements ActionListener
        {
            public void actionPerformed(ActionEvent event)
            {
                System.out.println("At the tone, the time is" +new Date());
                if (beep) Toolkit.getDefaultToolkit().beep();
            }
        }
        ActionListener listener = new TimePrinter();
        Timer t = new Timer(interval, listener);
        t.start();
    }

    流程:
        1.调用start方法
        2.调用内部类TimePrinter的构造器,一边初始化对象变量listener
        3.将listener引用传递给Timer构造器,定时器开始计数时,start方法结束。
        4.然后actionPerformed方法执行if
  • 匿名内部类

只创建这个类的一个对象,就不必命名,这种类被称之为匿名内部类。

   public void start(int interval, boolean beep)
    {
        ActionListener listener = new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {
                System.out.println("At the tone, the time is" + new Date());
                if (beep) Toolkit.getDefaultToolkit().beep();
            }
        };
        Timer t = new Timer(interval, listener);
        t.start();
    }

含义:创建一个实现ActionListener接口的类的新对象,需要实现的方法actionPerformed定义在括号{}内。

语法格式:
    new SuperType(construction parameters)
    {
        inner class methods and data
    }
  • 静态内部类

将内部类声明为static。
考虑一下计算数组中的最小值和最大值的问题。同时计算出最小值和最大值。

double min = Double.POSITIVE_INFINITY;
double max = Double.NECATIVE_INFINITY;
for (double v : values)
{
if (min > v) min = v;
if (max < v) max = v;
}

class ArrayAlg
{
public static Pair minmax(doublet] values)
{

return new Pair(min, max) ;
}
}
使用方法:
Pair p = ArrayAlg.minmax(d);
System,out.println("min = " + p.getFirst());
System,out.println("max = " + p.getSecond());

6.5 Proxy

Agents can use to create an implementation of a set of new classes given interface at runtime.

  • When to use a proxy

Agent with the following method:
All A method specified interface required.
All methods 2.Object class.

  • Creating a proxy object

We want to create a proxy object, use newProxyInstance methods of the Proxy class. The parameters are:
1. a class loader.
2. A Class array of objects, each element needs to implement.
3. a call processor.

Published 14 original articles · won praise 22 · views 558

Guess you like

Origin blog.csdn.net/qq_41550921/article/details/103999206