Home Java Javagetting Started What can be the modifiers of java interface

What can be the modifiers of java interface

Jan 04, 2023 pm 01:04 PM
java

The modifiers of java interface can be abstract and final. The interface can be understood as a special class. The difference is that the members of the interface have no execution body and are composed of global constants and public abstract methods; the methods of the interface are public abstract by default; and variables cannot be defined in the interface. Constants can be defined (with final modification, they will become constants), so the properties of the interface are public static final constants by default and must be assigned an initial value.

What can be the modifiers of java interface

The operating environment of this tutorial: windows7 system, java8 version, DELL G3 computer.

Abstract class is a template abstracted from multiple classes. If this abstraction is carried out more thoroughly, a more special "abstract class" - interface (Interface) can be extracted. Interface is one of the most important concepts in Java. It can be understood as a special class. The difference is that the members of the interface have no execution body and are composed of global constants and public abstract methods.

Define interface

The definition of Java interface is basically the same as that of class, but the keyword used in interface definition is interface, and the syntax of interface definition is The format is as follows:

[public] interface interface_name [extends interface1_name[, interface2_name,…]] {
    // 接口体,其中可以包含定义常量和声明方法
    [public] [static] [final] type constant_name = value;    // 定义常量
    [public] [abstract] returnType method_name(parameter_list);    // 声明方法
}

The description of the above syntax is as follows:

  • public represents the modifier of the interface. When there is no modifier, the default modifier is used. This The access rights of the interface are limited to the package to which it belongs;

  • interface_name represents the name of the interface. The interface name should adopt the same naming rules as the class name, that is, from a grammatical perspective, the interface name only needs to be a legal identifier. To comply with Java readability specifications, an interface name should be a concatenation of meaningful words, with the first letter of each word capitalized, without any separators between words.

  • extends represents the inheritance relationship of the interface;

  • interface1_name represents the name of the interface to be inherited;

  • constant_name represents the variable name, usually static and final;

  • returnType represents the return value type of the method;

  • parameter_list represents the parameter list , methods in interfaces have no method body.

Note: An interface can have multiple direct parent interfaces, but interfaces can only inherit interfaces, not classes.

Modifiers of java interface

The interface is very important. In order to explain the situation, here is a little more verbose:

(1) The interface is used to describe all services provided by the system to the outside world, so the member constants and methods in the interface must be of public type to ensure that external users can access them;

(2) The interface only describes what the system can do, but does not specify how to do it, so the methods in the interface are abstract methods;

(3) The interface does not involve details related to any specific instance, so the interface There is no constructor, it cannot be instantiated, there are no instance variables, only static variables;

(4) The variables in the interface are common to all implementation classes. Since they are common, they must be unchanged. , because things that change cannot be counted as shared. Therefore, the variable is an immutable (final) type, which is a constant.

(5) Variables cannot be defined in the interface? If the interface can define variables, but the methods in the interface are abstract, the properties cannot be modified through behavior in the interface. Some people will say, it doesn't matter, you can modify the properties in the interface through the behavior of the object that implements the interface. This is of course no problem, but consider this situation. If there is a static variable a with public access in interface A. According to Java's semantics, we can access variable a without using the object that implements the interface. We can change the value of variable a in the interface through A.a = xxx;. Just as this can be done in an abstract class, all objects that implement interface A will automatically have the changed value of a. That is to say, if a is changed in one place, the value of a in all these objects will also follow. changed. What is the difference between this and an abstract class? How to reflect the higher abstraction level of the interface? How to reflect the unified protocol provided by the interface? Then what is the use of the abstraction of the interface? Therefore, variables cannot appear in the interface. If there are variables, it conflicts with the idea of ​​unified abstraction provided by the interface. Therefore, the attributes in the interface must be constants, which can only be read and cannot be changed. Only in this way can a unified attribute be provided for the object that implements the interface.

In layman's terms, if you think something needs to be changed, put it in your own implementation and not in an interface. An interface is just a higher-level abstraction of the attributes and behaviors of a type of thing. Closed for modification and open for extensions (different implementations), the interface is a manifestation of the open-closed principle.

So:

The default method of the interface is public abstract;

You cannot define variables in the interface, only constants (plus final modification) will become a constant). Therefore, the properties of the interface are public static final constants by default, and must be assigned an initial value.

Note: final and abstract cannot appear at the same time.

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of What can be the modifiers of java interface. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1503
276
go by example http middleware logging example go by example http middleware logging example Aug 03, 2025 am 11:35 AM

HTTP log middleware in Go can record request methods, paths, client IP and time-consuming. 1. Use http.HandlerFunc to wrap the processor, 2. Record the start time and end time before and after calling next.ServeHTTP, 3. Get the real client IP through r.RemoteAddr and X-Forwarded-For headers, 4. Use log.Printf to output request logs, 5. Apply the middleware to ServeMux to implement global logging. The complete sample code has been verified to run and is suitable for starting a small and medium-sized project. The extension suggestions include capturing status codes, supporting JSON logs and request ID tracking.

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Comparing Java Build Tools: Maven vs. Gradle Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

How to read a CSV file in Java? How to read a CSV file in Java? Aug 03, 2025 am 11:56 AM

Using the OpenCSV library is the best choice for reading CSV files. It can handle complex situations and supports multiple features; 2. For simple CSV files, you can use Java's built-in BufferedReader combined with split method; 3. If you need more flexible format control or have used Apache components, you can choose Apache CommonsCSV. OpenCSV is recommended for its simplicity, robustness and ability to handle CSV problems in real scenarios.

Volume keys on keyboard not working Volume keys on keyboard not working Aug 05, 2025 pm 01:54 PM

First,checkiftheFnkeysettingisinterferingbytryingboththevolumekeyaloneandFn volumekey,thentoggleFnLockwithFn Escifavailable.2.EnterBIOS/UEFIduringbootandenablefunctionkeysordisableHotkeyModetoensurevolumekeysarerecognized.3.Updateorreinstallaudiodriv

How to compare two strings in Java? How to compare two strings in Java? Aug 04, 2025 am 11:03 AM

Use the .equals() method to compare string content, because == only compare object references rather than content; 1. Use .equals() to compare string values equally; 2. Use .equalsIgnoreCase() to compare case ignoring; 3. Use .compareTo() to compare strings in dictionary order, returning 0, negative or positive numbers; 4. Use .compareToIgnoreCase() to compare case ignoring; 5. Use Objects.equals() or safe call method to process null strings to avoid null pointer exceptions. In short, you should avoid using == for string content comparisons unless it is explicitly necessary to check whether the object is in phase.

Computed properties vs methods in Vue Computed properties vs methods in Vue Aug 05, 2025 am 05:21 AM

Computed has a cache, and multiple accesses are not recalculated when the dependency remains unchanged, while methods are executed every time they are called; 2.computed is suitable for calculations based on responsive data. Methods are suitable for scenarios where parameters are required or frequent calls but the result does not depend on responsive data; 3.computed supports getters and setters, which can realize two-way synchronization of data, but methods are not supported; 4. Summary: Use computed first to improve performance, and use methods when passing parameters, performing operations or avoiding cache, following the principle of "if you can use computed, you don't use methods".

How to join an array of strings in Java? How to join an array of strings in Java? Aug 04, 2025 pm 12:55 PM

Using String.join() (Java8) is the easiest recommended method for connecting string arrays, just specify the separator directly; 2. For old versions of Java or when more control is needed, you can use StringBuilder to manually traverse and splice; 3. StringJoiner is suitable for scenarios that require more flexible formats such as prefixes and suffixes; 4. Using Arrays.stream() combined with Collectors.joining() is suitable for filtering or converting the array before joining; To sum up, if Java8 and above is used, the String.join() method should be preferred in most cases, which is concise and easy to read, but for complex logic, it is recommended.

See all articles