Home > Java > javaTutorial > body text

How to call interface in java

下次还敢
Release: 2024-04-26 21:30:25
Original
857 people have browsed it

To call the methods of an interface, you need to create a class that implements the interface, and then call the methods of the interface just like calling methods of other classes. Interfaces cannot be instantiated, only implemented. Methods in interfaces are abstract by default and cannot have constructors. An interface variable can refer to an instance of any class that implements the interface. Two interfaces cannot be directly related through inheritance, but it is possible to create classes that implement multiple interfaces.

How to call interface in java

How to call interface in Java

In Java, an interface is a class that contains only abstract methods. Interfaces cannot be instantiated, but they can be implemented. A class that implements an interface must provide concrete implementations of all abstract methods in the interface.

How to call the interface

To call the method of the interface, you need to first create a class that implements the interface. The interface's methods can then be called just like any other class's methods.

For example:

<code class="java">// 定义一个接口
interface Shape {
    void draw();
}

// 实现接口
class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a rectangle");
    }
}

// 调用接口的方法
Shape shape = new Rectangle();
shape.draw();</code>
Copy after login

Output:

<code>Drawing a rectangle</code>
Copy after login

Note:

  • In the interface The methods are abstract by default and do not need to be explicitly declared abstract.
  • Interfaces cannot have constructors.
  • Interface variables can reference any instance of a class that implements the interface.
  • Two interfaces cannot be directly related through inheritance. However, it is possible to create classes that implement multiple interfaces.

The above is the detailed content of How to call interface in java. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!