Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Essential example Analysis of Java Interface

2025-02-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article, the editor introduces "the essential case analysis of Java interface" in detail. The content is detailed, the steps are clear, and the details are handled properly. I hope this "essential example analysis of Java interface" article can help you solve your doubts.

Interface

Java interface is the declaration of a series of methods and a collection of method characteristics. An interface has only method characteristics but no method implementation, so these methods can be implemented by different classes in different places, and these implementations can have different behaviors (functions).

Definition of Interfac

Interface:

In the JAVA programming language, it is an abstract type, a collection of abstract methods, and interfaces are usually declared as interface. A class inherits the abstract methods of an interface by inheriting the interface. The interface is a more thorough abstraction, and the interface is full of abstract methods. (before JDK8), interfaces also cannot create objects.

And in order to make up for the disadvantage that we can only inherit only in previous inheritance, Java provides us with an interface, which can implement multiple interfaces.

Interface is more like expressing a kind of ability specification, just like we defined animals before, animals have the behavior method of eating, while other animals that have implemented the animal interface class must implement the behavior method of eating. So its function mainly tells the implementation class that you have to implement the functions I have in it.

So what's the difference between interface and abstraction?

The difference between interface and abstraction

The method in the abstract class can have the method body, that is, it can implement the concrete function of the method, but the method in the interface is not.

Member variables in an abstract class can be of various types, while member variables in an interface can only be of type public static final.

An interface cannot contain static code blocks and static methods (methods decorated with static), while abstract classes can have static code blocks and static methods.

A class can inherit only one abstract class, while a class can implement multiple interfaces.

Note:

After JDK 1.8, there can be static methods and method bodies in the interface, and the interface is allowed to contain specific implementation methods, which are called default methods, and the default methods are modified with the default keyword.

Let's take a look at the specific study.

Format of the interface

Mainly through the interface keyword modification on the class, making it an interface class! All methods in an interface must declare only the method identity, not the specific method body.

/ / format of the API:

Modifier interface interface name {

/ / Abstract method

Void eat ()

}

If the class needs to implement the keyword implements of the interface.

Points to pay attention to in the process of implementation:

All abstract methods in all interfaces of the implementation must be overridden.

If a class implements an interface but does not rewrite all abstract methods for all interfaces, the class must also be defined as an abstract class.

/ / implement the format of the API:

Modifier class class name implements interface name {

/ / implement all abstract methods in the interface

Void eat () {}

}

/ / format of multiple implementations:

Modifier class class name implements interface 1, interface 2, interface 3. {

/ / Abstract method

Void eat ()

....

}

The main components of the interface

Let's talk about the components of the interface before JDK8: abstract methods and constants.

Abstract method:

The abstract methods in the interface are automatically decorated with public abstract by default. Programmers do not have to write by hand!

According to the specification: abstract methods in future interfaces are not recommended to write public abstract. Why? Because it is not necessary, it will be added by default.

Package src.com.na.pojo;/** * first define an interface parent class-- > animal class * all animals have an abstract method to eat * / public interface Animal {/ / is defined as an abstract method, there is no need to implement the method entity! / / the default modifier is that public abstract can be ignored or not written! / / public abstract void eat (); / / this is also possible. Public abstract void eat ();} constant is ignored by default:

In the interface, the member variables we define are decorated with: public static final by default.

What does this mean? the member variable defined in the interface is actually a constant, and we know that the variable modified by the final keyword is immutable and statically modified by static, which means that we can access it directly with the interface name.

And we are defining member variables, that is, constants, that must be given initial values.

Package src.com.na.pojo;/** * first define an interface parent class-- > animal class * all animals have an abstract method to eat * / public interface Animal {/ / define that the member variable is constant / / the default modifier is that public static final can be ignored and not written! / / public static final String NAME = "animal"; String NAME = "animal";}

Note: the constant naming convention recommends that all letters are capitalized and multiple words are connected with an underscore. That is ANIMAL_NAME

Case of Interfac

Let's take the athlete as an example this time, this Su God, I saw it on a whim, which is much more warm-blooded than the popular biography and Altman.

Define the athlete interface

Package src.com.na.pojo;/** * defines an interface class for athletes, which can be divided into many categories: track and field athletes, weightlifters, table tennis players, etc. * defines some norms between these athletes. * / public interface SportMan {/ / for example: athletes, can exercise, there are corresponding events bar void project (); / / athletes will have competition results, the results. Void performance (); / / what competitions will athletes take part in and what awards will they get? which place will they rank? String competition (String project);}

Define the subcategory of track and field athletes to implement the athlete interface

Package src.com.na.pojo;/** * defines a track and field athlete, Su Shen yyds! 9.83s * / public class AthleticsMan implements SportMan {/ * after implementing the interface, you must rewrite all abstract methods in it! * / @ Override public void project () {System.out.println ("Su Shen participated in the 100m event at the Olympic Games!") ;} @ Override public void performance () {System.out.println ("Su Shen made history, representing Asians can make it to the 100m final! and set an Asian record of 9.83s in the final!") @ Override public String competition (String project) {return "Su Bingtian took part in" + project+ "and won the sixth place! yydsfolk!";}

Define the test class:

Package src.com.na;import src.com.na.pojo.AthleticsMan;/** * Test Interface * / public class Demo {public static void main (String [] args) {AthleticsMan suBingTian = new AthleticsMan (); suBingTian.project (); suBingTian.performance (); System.out.println (suBingTian.competition ("100m");}}

Results:

Su Shen participated in the 100-meter event in the Olympic Games!

Su Shen made history, representing that Asians can rush to the 100-meter final and enter the final! And set an Asian record of 9.83 million dollars!

Su Bingtian won the sixth place in the 100 meters! Yyds!!!

The relationship between interface and interface

We know that there can be inheritance relationships between classes, and our interfaces and classes are implementation relationships, so what about the relationship between interfaces?

In Java, interfaces can inherit from one interface to another: that is, an interface can inherit multiple interfaces at the same time. It is equivalent to merging the abstract methods of other interfaces with this interface in inheritance.

The code is as follows:

Package src.com.na;public class Demo2 {} / / run interface interface Run {void run ();} interface Project {void Project ();} / * * Summary: * there are multiple implementations between interfaces and classes. * there is multiple inheritance between interfaces. * * / interface SportMan2 extends Run, Project {String competition (String project); / / Abstract method, competition. } method added to the interface after JDK 8

After the start of JDK 8, the interface no longer seems to be pure!

The interface is no longer just abstract methods, the interface can also have default methods (that is, instance methods) and static methods, as well as private instance methods and private static methods

1. Contains default and static methods

The default method: use default modification, can not be omitted, for subclass calls or subclass overrides.

Static method: modified by static, which can be called directly by the interface.

The code is as follows:

Package src.com.na.pojo;/** * Test interface can contain default method and static method * / public interface InterfaceTest {/ / contains default method, default keyword public default void defaultMethod () {System.out.println ("default method");} / / contains static method, static keyword public static void staticMethod () {System.out.println ("static method") }} 2. Contains private methods and private static methods

Private methods: decorated with private for default or static method calls in the interface.

Private static methods: use private decorations, use static decorations.

The code is as follows:

Package src.com.na.pojo;/** * the test interface can contain private methods and private static methods * / public interface InterfaceTest2 {/ / contains private methods, and private modifies private void privateMethod () {System.out.println ("private methods") } / / contains private static methods, static keyword, private modifies private static void privateStaticMethod () {System.out.println ("private static methods");}} the characteristics of ‍♂️ API:

The methods in the interface are all abstract methods and are automatically decorated with public abstract by default.

Interface, member variables cannot be defined, but constants can be defined, their values cannot be changed, and public static final modifiers are used by default.

There is no constructor in the interface, so objects cannot be created!

The relationship between classes and interfaces is multi-implemented.

The relationship between interface and interface is multi-inherited.

The interface is more of a specification.

Starting with JDK 8, the interface is no longer pure and supports static methods, default methods, and private methods.

After reading this, the article "essential example Analysis of Java Interface" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself to understand it. If you want to learn more about related articles, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report