Java object-oriented interface (interface) (1)

Source: Internet
Author: User

Java object-oriented interface (interface) (1)
I. Java Interface

An interface is a set of abstract methods and constant values. It is an abstract type in Java programming language.

Ming. A class is a specific implementation body, and an interface defines the specifications that a batch of classes need to comply with. The interface does not care about the internal data of these classes or

The implementation details of methods in the class, which only specifies that some methods must be provided in these classes. A class or interface inherits

Abstract method.

Interfaces are not classes. interfaces are similar to classes, but they belong to different concepts. Class describes the attributes and methods of an object. The Interface contains

Class. Unless the class implementing the interface is an abstract class, the class must define all methods in the interface.

In essence, an interface is a special abstract class that only contains the definition of constants and methods, without the implementation of variables and methods, and

The class keyword is not used for defining an interface, but the interface keyword is used.

The interface cannot be instantiated, but can be implemented. A class that implements an interface must implement all the methods described in the interface; otherwise, it must be declared

Is an abstract class. In addition, in Java, the interface type can be used to declare a variable. They can be a null pointer or bound to an interface

Implementation object.

2. interface declaration

Interfaces are inherited and implemented. Therefore, public or default modifiers are recommended. private and protected cannot be used for repairs.

Decoration interface. The interface keyword is used to declare an interface.

The Declaration syntax of the interface is as follows:

A static constant: the attribute in the interface is A constant. Even if the public static final modifier is not added during definition, the system automatically adds the modifier.

B. abstract method: Methods in an interface can only be abstract methods. They are always used. Even if the public abstract modifier is not added during definition, the system automatically

Add.

Therefore, the interface definition format is:

 

[Modifier] interface name [other interface names of extends] {// declare static constants // declare Abstract METHODS}

 

The following is a simple example of interface declaration.

NameOfInterface. java source file code:

 

Import java. lang. *; // introduce the public interface NameOfInterface package {// any type of static, final field // abstract method}

 

Interfaces have the following features:

(1) The interface can be implemented in multiple ways;

(2) declared attribute in the interface is public static final by default, and can only be public static final;

(3) only abstract method methods can be defined in the interface. By default, these methods are public and only public. Each method in the interface is also implicit.

Abstract: The abstract key sub-statement is not required during declaration;

(4) interfaces can inherit other interfaces and add new attributes and abstract methods;

(5) Multiple irrelevant classes can implement the same interface;

(6) A class can implement multiple irrelevant interfaces;

(7) similar to inheritance, There Is A polymorphism between interfaces and implementation classes.

Instance:

Animal. java source file code:

 

Interface Animal {// static constant member public static final int AGE = 5; // abstract method member public void eat (); public void travel ();}

 

Implementation of three interfaces

When a class implements an interface, the class must implement all methods of the interface. Otherwise, the class must be declared as an abstract class. Class Using implements keyword

Current interface. In the class declaration, the implements keyword is placed after the class declaration. You can use this formula to implement the syntax of an interface:

... Implements interface name [, other interfaces, other interfaces...,...]...

Instance

Continue to implement the interface declared in the above instance:

Mammal. java source file code:

 

Public class Mammal implements Animal {// rewrite the eat () method public void eat () {System in the Animal interface. out. println ("Mammal eats");} // rewrite the travel () method public void travel () {System. out. println ("Mammal travels");} // The noOfLegs () method exclusive to the Mammal class public int noOfLegs () {return 0;} public static void main (String args []) {Mammal m = new Mammal (); m. eat (); m. travel ();}}
The above example compilation and running results are as follows:

 

When rewriting the abstract method member declared in the interface, you must pay attention to the following rules:

(1) When a class implements an interface method, it cannot throw a mandatory exception. It can only be thrown in an interface or an abstract class that inherits the interface.

(2) The method names must be consistent during method rewriting, And the return value types should be the same or compatible.

(3) If the class implementing the interface is an abstract class, there is no need to implement the method of this interface.

When implementing interfaces, pay attention to the following rules:

(1) A class can implement multiple interfaces at the same time.

(2) A class can inherit only one class, but can implement multiple interfaces.

(3) one interface can inherit another interface, which is similar to the inheritance between classes.

Four interface inheritance

One interface can inherit from another interface, which is similar to the Inheritance Method between classes. The extends keyword is used for interface inheritance. The sub-interface inherits the parent interface.

.

The following Sports interfaces are inherited by the Hockey and Football interfaces:

Sports. java source file code:

 

Public interface Sports {// abstract method public void setHomeTeam (String name); public void setVisitingTeam (String name );}

 

Hockey. java source file code:

 

Public interface Hockey extends Sports {// Hockey interface's own abstract method public void homeGoalScored (); public void visitingGoalScored (); public void endOfPeriod (int period ); public void overtimePeriod (int ot );}
Football. java source file code:

 

 

Public interface Football extends Sports {// The Football interface's own abstract method public void homeTeamScored (int points); public void visitingTeamScored (int points); public void endOfQuarter (int quarter );}
The Hockey interface declares four methods and inherits two methods from the Sports interface. In this way, the class that implements the Hockey interface must implement six methods.

 

Method. Similarly, classes that implement the Football interface need to implement five methods, two of which are from the Sports interface.

Multi-inheritance of five Interfaces

In Java, multi-inheritance of classes is illegal, but interfaces allow multi-inheritance. In the multi-inheritance of interfaces, only one of the extends keywords is required.

And then inherit the interface. As follows:

 

public interface Hockey extends Sports, Event{       }

 

The preceding program fragment is a legally defined sub-interface. Unlike the class, the interface allows multi-inheritance, while Sports and events may be defined or inherited.

Same method.

Vi. Identification Interface

The most common inherited interface is an interface that does not contain any methods. The ID interface is an interface without any methods and attributes. It only indicates that its class belongs

A specific type for other code to test whether something can be done.

Identity interface function: Simply put, an object is labeled (stamped) so that the object has some or some privileges.

For example, under the definition of java. util. EventListener inherited by the MouseListener interface in the java. awt. event package:

 

Package java. util; public interface EventListener {// class body details}

 

An interface without any method is called a tag interface. The tag interface is mainly used for the following two purposes:

(1) create a public parent interface

Like the EventListener interface, This is a Java API extended by dozens of other interfaces. You can use a tag interface to create a group of interface parent

Interface. For example, when an interface inherits the EventListener interface, the Java Virtual Machine (JVM) knows that the interface will be used by the agent of an event.

Case.

(2) Add data types to a class

 

This is the initial purpose of marking an interface. The class implementing the marking interface does not need to define any interface methods (because the marking interface does not have a method at all ),

However, this type is changed to an interface type through polymorphism.

Class 7 inherits the parent class and the implemented Interface

To inherit a parent class, the parent class must be inherited before the interface is implemented. Inherit the syntax of the parent class implementation interface:

 

[Modifier] class name extends parent class implements interface 1, interface 2... {class part // If the abstract class is inherited, the inherited abstract method must be implemented; the abstract method in the interface must be implemented .}

 

 

Instance:

Demo. java source file code:

 

Public class Demo {public static void main (String [] args) {Dog d1 = new Dog (); d1.eat (); d1.run () ;}} class Animal {public String name; public int age; public void eat () {System. out. println ("Animal food capabilities");} interface Runner {public void run ();} class Dog extends Animal implements Runner {public void eat () {System. out. println ("dogs have the ability to eat bones");} public void run () {System. out. println ("the dog has the ability to run ");}}

 

Running result:

Summarize the similarities between the interface and the class:

(1) An interface can have multiple methods.

(2) The interface file is saved in the file ending with. java, and the file name uses the interface name.

(3) The interface bytecode file is stored in the file ending with. class.

(4) the corresponding bytecode file of the interface must be in the directory structure that matches the package name.

Differences between interfaces B and classes:

(1) The interface cannot be used to instantiate objects.

(2) The interface does not have a constructor.

(3) All methods in the interface must be abstract methods.

(4) The interface cannot contain member variables except static and final variables.

(5) the interface is not inherited by the class, but implemented by the class.

(6) interfaces support multiple inheritance; classes only support single inheritance.

 

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.