Java core technology-interfaces, lambda expressions, and internal classes

Source: Internet
Author: User
Tags comparable modifier shallow copy variable scope java se



This chapter will mainly introduce:



Interface technology: Primarily used to describe what functions a class has, and does not give a specific implementation of each feature. A class can implement one or more interfaces.



Lambda expression: This is a neat way to represent a block of code that can be executed at a later point in time.



Inner class mechanism: The inner class is defined inside another class, where methods can access the domain of the outer class that contains them.



Proxy: An object that implements any interface.


1 Concept of Interface 1.1 interface


Concept: An interface is not a class, but a set of requirements descriptions for a class that is defined in accordance with the uniform format of the interface description.



"If the class complies with a particular interface, then perform the service":



The sort method in the arrays class promises to sort the array of objects, but requires that the class to which the object belongs must implement the comparable interface.



All methods in the interface automatically belong to public. Therefore, when declaring a method in an interface, you do not have to provide the keyword public.



A constant can be defined in an interface, but must not contain an instance domain, and after Java SE 8, you can provide a simple method in the interface (cannot reference the instance domain)



The task that provides the instance domain and method implementation should be done by the class that implements the interface, and you can think of the interface as an abstract class without an instance domain.



In order for the class to implement an interface, a step is required:



1. Declare the class to implement the given interface (implements keyword).



2. Define all the methods in the interface (when implementing an interface, the method must be declared public).



Reasons for implementing an interface without directly providing a CompareTo method:



Java is a strongly typed language, and the compiler checks to see if the method exists when the method is called. The class that implements the Compareble interface must exist in this way.


1.2 Features of the interface


An interface is not a class, so you cannot instantiate an interface with new, but you can declare the variables of the interface, and the interface variable must refer to the class object that implements the interface.



Use instanceof to check whether an object belongs to a particular class, use instance to check whether an object implements a particular interface



The constants in the interface are automatically set to public static final.



Although each class can have only one superclass, it can implement multiple interfaces. This provides a great deal of flexibility in defining the behavior of the class. (Separate each interface implemented with a comma)


1.3 Interfaces and abstract classes


The difference between an interface and an abstract class:



The use of abstract classes to represent common properties exists that each class can only extend problems with one class, but each class may implement multiple interfaces.


1.4 Static methods


In Java SE 8, static methods are allowed to be added to the interface.



So far, the usual practice is to put static methods in the accompanying class. In the standard library, you will see paired interfaces and use tool classes, such as Collection/collections or path/paths.



This adjoint class implements some or all of the corresponding interface methods.



Now as long as the static method is added when implementing the interface, it is no longer necessary to provide another companion class for using the tool method.


1.5 default method


You can provide a default implementation for an interface method. Such a method must be marked with the default modifier.



The class that implements this interface can optionally override the default method in the interface.



An important use of the default method is the interface evolution (adding the default method to the previously designed interface, without recompiling all classes that implement the interface before recompiling and invoking the implementation in the interface when the newly added method is called)


1.6 Resolving default method conflicts


Consider what happens if you define a method as the default method in one interface, and then define the same method in a superclass or another interface. (ambiguity)



The Java processing rules are as follows:



1. Super class first (considering the compatibility of the interface new default method)



2. Interface conflicts: Consider three scenarios



1. The default implementation of this method is available in two interfaces-this method must be overridden to resolve the conflict (you can choose one of the two conflicting methods to provide the default implementation)



2. There is a default implementation of this method in two interfaces--you must override this method to resolve the conflict (you can choose the one that provides the default implementation in the two conflicting methods)



3. The default implementation of this method is not available in two interfaces-this method can be implemented, or it may not be implemented. If not implemented, the class itself is abstract





2 Interface Example 2.1 interface and callback


Callbacks are a common programming pattern. In this mode, you can indicate the action that should be taken when a particular event occurs.


ActionListener listen=New  timeprinter (); Timertime =new timer (10000,listen)
2.2 Comparator interface


Consider a situation like this:



A class itself already inherits the comparable interface, which has a Comparato method sorted by dictionary order. Now we want to sort this class in ascending order of length. Instead of sort by dictionary.



To solve this situation, consider using an array and a comparer as parameters, and the comparator is an instance of the class that implements the comparator interface.


comparator<string> comp=New  lengthcomparator (); if (Comp.compare (words[i],words[j]) >0 ...


Compare this call with Words[i].compareto (Words[j]). This compare method is called on the comparator object, not on the string itself.



The difference between comparator and comparable:



1. You need to establish a comparator specific instance when using comparator for comparison



The 2.Comparator call object is the comparer, and the comparable call object is the string itself



3. Use of comparator to achieve a more diverse approach to comparison


2.3 Object Cloning


This section discusses the Cloneable interface, which indicates that a class provides a secure Clone method



Consider a situation like this:



When we make a copy of a variable that contains an object reference, both the original variable and the copy are references to the same object. This means that any change in one variable will affect the other.


Employee origina=New employee ("John Public", 50000); Employee copy=original;copy.raisesalary (10);


If you want copy to be a new object, its initial state is the same as original, but then they will each have their own different states, in which case you can use the Clone method.


Employee copy=original.clone (); Copy.raisesalary (10);


The default clone operation is a shallow copy , and there are no other objects referenced in the cloned object.



If all the child objects in the original object are immutable, it is safe to use a shallow copy.



If the sub-object belongs to an immutable class, you need to use a deep copy .



For each class, you need to determine:



1. Whether the default clone method satisfies the requirements;



2. Whether clone can be called on a mutable sub-object to fix the default clone method;



If you select the first or second item, the class must:



1. Implement cloneable interface;






The Clone method in object is declared as protected, so it is necessary to  it as public in the implementation class in order to invoke the Clone method of the instantiated implementation class object in other classes.



The Cloneable interface is a markup interface, and the markup interface does not contain any methods; its only function is to allow the use of instanceof in type queries



If clone is called on an object, but the class of the object does not implement the Cloneable interface, the Clone method of object class throws a clonenotsupportedexception.



All array types have a clone method of public





3 lambda expression


Use a concise syntax to define code blocks


3.1 Why lambda expressions are introduced


A lambda expression is a transitive block of code that can be executed one or more times at a later time.



such as passing a class instance that implements the ActionListener interface to a timer or implementing a class instance of the comparator interface to the sort method.


3.2 The syntax of a lambda expression
(String first,string second)  ->first.length ()-second.length ()


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



Empty parentheses are provided even if the lambda expression has no arguments


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


If you can deduce the parameter type of a lambda expression, you can omit its type


comparator<string> Comp =(first,second) ->first.length ()-second.length ();


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


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


You do not need to specify the return type of a lambda expression



It is illegal for a lambda expression to return only one value in some branches, but not to return a value in some other branches.


(int x)->{if(x>=0)return 1;}
3.3 Function-type interface


Concept: An interface with only one abstract method is called a functional interface



You can replace a functional interface with a lambda expression



For example: Comparator is an interface with only one method, so you can provide a lambda expression


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


At the bottom, the Arrays.sort method receives the object of a class that implements the Comparator<string>. Calling the Compare method on this object executes the body of the lambda expression. (to accept that a lambda expression can be passed to a functional interface)



It's a good idea to think of a lambda expression as a function, not an object.



In fact, in Java, a lambda expression can only be converted to a functional interface.


3.4 Method Reference


To use:: Operators to separate method names from object or class names, there are three main cases:



*object::instancemethod



*class::staticmethod



*class::instancemethod



In the first two cases, a method reference is equivalent to a lambda expression that provides a method parameter:



Expression System.out::p Rintln is a method reference that is equivalent to a lambda expression x->system.out.println (x)



Expression Math::p ow is a method reference that is equivalent to a lambda expression (x, y)->math.pow (x, y)



For a third case, the first parameter becomes the target of the method:



The expression String:;comparetoignorecase is a method reference, which is equivalent to (x, y)->x.comparetoignorecase (y)



Similar to lambda expressions, method references cannot exist independently and are always converted to instances of a functional interface



You can use this and the super parameter in a method reference



This::equals equivalent to X->this,equals (x)


3.5 constructor Reference


A constructor reference is similar to a method reference, except that the method name is new. For example, Person::new is a reference to the person constructor. Which constructor is called depends on the context.



You can establish a constructor reference with an array type, for example, Int[]::new is a constructor reference, equivalent to a lambda expression x->new int[x]



Java has a limitation that an array of generic type T cannot be constructed. Array constructor references are useful for overcoming this limitation.


3.6 Variable Scope


In general, you might want to be able to access variables in a perimeter method or class in a lambda expression.



Example:


 Public Static void repeatmessage (String text,int  delay) {    ActionListener listener=event->  {            System.out.priintln (text);            Toolkit.getdefaulttoolkit (). Beep ();        };  New Timer (Delay,listener). Start ();}


The code for the lambda expression may run long after the repeatmessage call returns, and the parameter variable no longer exists. How do I keep the text variable?



A lambda expression consists of the following three parts:



1. a block of code;



2. Parameters;



3. The value of a free variable, which refers to a variable that is not a parameter and is not defined in the code.



In Java, a lambda expression is a closure.



Java core technology-interfaces, lambda expressions, and internal classes


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.