[Java Learning notes] Java Core Technology Volume 1 The sixth chapter interface and inner class

Source: Internet
Author: User
Tags comparable

Chapter 6th interface and internal Class 6.1 interface

A class can implement one or more interfaces and use objects that implement the corresponding interface at any time where the interface is needed.

In an interface declaration, a method is automatically public and can be written without a modifier. The method must be declared as public when implementing the interface.

You can include multiple methods in an interface, and you can define constants to automatically set public static final

The inner class declared in the interface automatically becomes the static and public class.

An interface cannot contain an instance domain, nor can it implement a method in an interface. The task that provides the instance domain and method implementation should be done by the class that implements the interface.

An interface can be thought of as an abstract class without an instance domain.

When the method is called, the compiler checks to see if the method exists, and if it is an array of objects that implement the interface, the method is provided in the interface, so it is certain that the method must be present. Each class that implements an interface must provide all the methods defined in the interface.

In order for a class to implement an interface, you need 1: Declare the class to implement implements given interface 2: Define all the methods in the interface.

 Public Interface comparable{   int  compareTo (Object Other);} class Implements comparable{...     Public int CompareTo (Object other)   {       employee E=(employee) other;        return Double.compare (salary,e.salary);    }}

Features of the 6.1.1 interface

The L interface is not a class, you cannot instantiate an interface with the new operator, but you can declare an interface variable, and the interface variable must refer to the class object that implements the interface.

New Comparable (...); // Error comparable x; // OK New Employee (...);

L Use instanceof to check if an object implements a specific interface

if instanceof Comparable) {...}

L As can inherit the class, can also extend the interface, the extension interface does not implement all the methods like implementing the interface

Some interfaces define only constants without a method, and any class that implements the interface automatically inherits these constants and can be consumed directly without the class name like a static domain. The form of a domain name

 Public Interface moveable{   void Move (doubledouble  y);}  Public Interface extends moveable{   double  Milespergallon ();    Double // Public static Final}

L Although each class can only have one superclass, it can implement multiple interfaces. Use commas to separate the implementation of each interface.

class Implements Cloneable,comparable
6.1.2 Interfaces and abstract classes

Abstract classes can also represent common properties, but there is a problem: each class can only be extended to (inherit) a class. Interfaces can implement multiple.

6.1.3 Tag Interface

The Cloneable interface is one of several markup interfaces provided by Java, and the markup interface has no method, and its sole purpose is to use instanceof for type checking.

Do not use this technique when writing your own programs.

6.2 Object Cloning

When copying a variable, the original variable references the same object as the copy variable, and changing the object referenced by one variable has an effect on the other variable.

The Clone method is an protected method of the object class that cannot be called directly in the user-written code. The object class knows nothing about the specific class object and can only copy the respective domains. There is no problem with a base type or a numeric copy, but if the object contains a reference to a child object, the result of the copy is two fields that refer to the same child object.

All default cloning operations are shallow copies and do not clone the internal objects contained in the object.

You must redefine the Clone method to implement a deep copy of the cloned sub-object. The following judgments are made for each class:

1: Whether the default Clone method meets the requirements

2: Whether the default Clone method can be patched by invoking the clone of a mutable child object.

3: If clone should not be used

If you want to use clone, you must:

1: Implement Cloneable interface

2: Use the public access modifier to redefine the Clone method and declare the exception clonenotsupportedexception

Even if the default implementation of clone satisfies the requirement, you should implement the Cloneable interface, define clone as public, and then call Super.clone ();

The Cloneable interface does not have any relation to the normal use of the interface. It does not have a clone method in place. The Clone method inherits from the object class. The interface is here as a marker, indicating that the Class designer is making the cloning process. If an object needs to be cloned without implementing the Cloneable interface, a checked exception is generated.

class Implements cloneable{...     Public throws clonenotsupportedexception   {       Employee cloned= (employee)Super. Clone (); // object.clone ()       Cloned.hireday= (Date) Hireday.clone (); // Cloning child Objects       return cloned;}   }

If the Clone method should be in advance, it should be implemented if the customer needs a deep copy. Cloned applications are also not very common, and only less than 5% of the classes in the standard class library implement clone.

All array types contain a clone method and are set to public, which can be used to create a new array containing copies of all the array elements.

6.3 Interfaces and callbacks

Callbacks can indicate the actions that should be taken when a particular event occurs.

Take the construction timer as an example:

In many programming languages, a function name can be provided, and the timer calls it periodically. However, classes in the Java Standard Class library take an object-oriented approach. Passing an object of a class to the timer, and then the timer, the timer invokes the method of the object. Because objects can carry some additional information, it is much more flexible to pass an object than to pass a function.

 Public Interfaceactionlistener{voidactionperformed (ActionEvent event);}classtimeprinter implenets actionlistener{ Public voidactionperformed (ActionEvent event) {//Do something small    }}//The object that constructs this class is passed to the timer constructorActionListener listener =NewTimeprinter (); Timer T=NewTimer (10000, listener);
6.4 Internal Classes

Why you need to use internal classes:

1: The inner class method can access the data in the scope where the class definition resides, including private data

2: Inner classes can be hidden from other classes in the same package

3: Using anonymous inner classes is convenient when you want to define a callback function and don't want to write a lot of code

6.4.1 accessing object state using an internal class

An object in an inner class always has an implicit reference to the outer class object that created it. References to objects of the perimeter class are referred to as outer.

Outer is not a Java keyword, the reference to the perimeter class is set in the constructor, and the compiler modifies the constructors for all inner classes, adding a reference parameter to the perimeter class.

Only the inner class can be a private class. A regular class can only have package visibility, or public visibility.

Special syntax rules for 6.4.2 inner classes

Using the Perimeter class reference: Outerclass.this

if (TalkingCLock.this.beep) ...

Constructor for writing an inner class object: Outerobject.new innerclass (contruction parameters)

ActionListener listener = this.new timerprinter ();

Reference the inner class outside the scope of the perimeter class:

Outerclass.innerclass

6.4.3 Internal class Security

If the inner class accesses the private data domain, it is possible to access them by attaching other classes in the Outer class shuttle, but doing so requires great skill and determination. It is not possible to gain access to the class unintentionally, and it is necessary to build or modify the class file to achieve this.

6.4.4 local Inner class

A partial class can be defined in a method and cannot be declared with the public or private access specifier, and its scope is scoped to the block that declares the local classes.

Local classes can be completely hidden from the outside world, even if other code in the class where the method is located cannot be accessed. There is no way to know the existence of a method other than defining it.

Another advantage of local classes is that you can access not only the external classes that contain them, but also local variables, but those local variables must be declared final

 Public voidStartintIntervalFinal Booleanbeep) {    classTimeprinterImplementsActionListener { Public voidactionperformed (ActionEvent event) {if(beep)//Local class access local variablesToolkit.getdefaulttoolkit (). Beep (); }} ActionListener Listener=NewTimeprinter (); Time t=NewTimer (Interval,listener); T.start ();}
6.4.5 Anonymous Inner class

If you create only one object of this (inner) class, you do not have to name it, and this class is called an anonymous inner class.

An anonymous class cannot have a constructor, and it needs to pass parameters to the superclass constructor, and the inner class cannot have any construction parameters when implementing the interface.

The constructor has the same name as the class name, and a class without a name cannot set the constructor.

Supertype can be an interface, the inner class will implement this interface, or it can be a class, and the inner class will extend it.

New supertype (Construction parameters) {   class  methods and Data}new  InterfaceType () {   methods and data}publicvoid start (intfinal  Boolean  beep) {   // Create a new object for the class that implements the Al interface   ActionListener listener =  New  ActionListener ()   {       ...   }   ...}
6.4.6 static Inner class

Sometimes an inner class is used only to hide one class inside another, and the inner class is not required to refer to the Outer class object. To do this, you can declare the inner class as static in order to cancel the resulting reference.

Only inner classes can be declared as static. An object of a static inner class is exactly the same as all other inner classes except that it does not have a referential privilege on the perimeter class object that generated it. If you construct an inner class in a static method, you must be a static inner class.

The inner class declared in the interface is automatically called the static and public classes.

6.5 Agents

It is not possible at compile time to determine which interface needs to be implemented, and the agent can create a new class that implements a given set of interfaces at run time.

For example, suppose you have a class object that represents an interface, and its exact type is not known at compile time. To construct a class that implements these interfaces, you need to use the Newinstance method or reflection to find the constructor for the class. However, you cannot instantiate an interface, and you need to define a new class when the program is in a running state.

To solve the above problem, some programs will generate code, then put the code in a file, call the compiler, and then load the result class file, it is obvious that this is slower, and need to put the compiler and the program together.

The proxy class can create a completely new class at run time, so that the proxy class can implement the specified interface, especially with the following methods:

1: Specify all the methods required for the interface

All methods in the 2:object class

However, new code for these methods cannot be defined at run time. To provide a calling processor, it is a class object that implements the Invocationhandler interface, where there is only one method

Object Invoke (Object proxy, Method method, object[] args)

Whenever a method of a proxy object is invoked, the Invoke method of the calling processor is called and passed to it with the methods object and the original invocation parameters. The calling processor must give a way to call processing.

To create a proxy object, you need to use the Newproxyinstance method of the proxy class, which has three parameters:

1: Class loader. As part of the Java security model, for system classes and from other classes, you can use a different classloader, currently using the default class loader with null notation

An array of 2:class objects. Each element is an interface that needs to be implemented

3: Call processor.

And there are two issues that need to be addressed:

1: How to define a processor

2: What to do with the result proxy object

6.6 Pending additions

Sample code for internal classes, proxies

[Java Learning notes] Java Core Technology Volume 1 The sixth chapter interface and inner class

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.