Table of Contents
基本概念
实例探究
嵌套接口
1.在类中定义接口
2.在接口中定义接口
接口&抽象类
1.语法区别
2.运用区别
Home Java javaTutorial 05.Java Basics - Interface

05.Java Basics - Interface

Feb 27, 2017 am 10:21 AM

基本概念

接口(interface),在软件工程中,接口泛指供别人调用的方法或者函数。它使抽象的概念更进一步。

在 Java 中通过关键字 interface 定义一个接口,通过关键字 implements 实现接口。

我们可以接口理解为是一个极度抽象的类,因为它比抽象类更抽象。


实例探究

下面通过例子来看接口的特点:

  • 定义一个接口

// 1.接口,访问权限只能是 默认(包访问权限)或 publicpublic interface Parent {

    // 2.成员变量,准确来说应该叫常量。具有以下特点:

    // 2.1.访问权限只能是 public (缺省也代表 public) ,修饰符只能是 final & static
    public final static String WORD = "a";    // 2.2.即使不指定,默认也是被 public fainl static 修饰
    String NAME = "b";    // 2.3.不能存在空的 final 变量 ,如 int num; 但是可以被非常量表达式初始化
    int num = new Random().nextInt(100);    // 3.抽象方法,访问权限只能是 默认(包访问权限)或 public
    public abstract void print();    abstract void print(int i);    // 4.普通方法,访问权限只能是 默认(包访问权限)或 public
    public void play();    void play(int i);
}
Copy after login
  • 实现一个接口

public class Son implements Parent {
    @Override
    public void print() {
        System.out.println("I am Son");
    }    @Override
    public void play() {
        System.out.println("Son is playing");
    }
}
Copy after login

嵌套接口

嵌套接口有两种形式:

  • 在类中定义一个接口;

  • 在接口中定义一个接口。


1.在类中定义接口

接口嵌套在类中,具有以下特点:

  • 接口的访问权限没了限制,可以使用 private 修饰

  • 方法/抽象方法/变量的访问权限与外部接口一致

下面通过实例来验证:

public class Demo {
    // 内部接口
    private interface A {
        void f();
    }    // 内部类
    class AImpl implements A {        @Override
        public void f() {
            System.out.println("AImpl.f()");
        }
    }

    A getA(){        return new AImpl();
    }    private A a;    public void receive(A a){        this.a = a;
        a.f();
    }
}
Copy after login

再来看它的调用过程:

Demo demo = new Demo();// 错误,因为 A 是私有接口,不可被外部访问
// Demo.A a = demo.getA();  // 因为 A 接口不可视,所以只能通过内部类来访问
Demo.AImpl a = (Demo.AImpl) demo.getA();a.f();// 或者是这样
demo.receiveA(demo.getA());
Copy after login

2.在接口中定义接口

在接口中定义接口,除了调用之外,均于普通接口一致。

public interface Demo {
    // 内部接口
    interface A {        void play();
    }    void print();
}public class DemoImpl implements Demo,Demo.A{

    @Override
    public void play() {
        System.out.println("DemoImpl.play()");
    }    @Override
    public void print() {
        System.out.println("DemoImpl.print()");
    }

}public class Test{
    public static void main(String[] args) {        // 向上转型,只能调用 print()
        Demo demo  = new DemoImpl();        // 向上转型,只能调用 play() 
        Demo.A a = new DemoImpl();      
    }
}
Copy after login

接口&抽象类

上面说过,我们可以把接口理解为是一个极度抽象的类,因为它比抽象类更抽象。

在实际运用中,两者还是有区别的。


1.语法区别

  • 抽象类可以包含非抽象方法,而接口中只能存在抽象方法。

  • 抽象类中的成员变量可以是各种类型的,而接口中的成员变量只能是公共的静态常量(public static final)。

  • 抽象类可以有静态代码块和静态方法,接口中不能含有静态代码块以及静态方法。

  • 一个类只能继承一个抽象类,而一个类却可以实现多个接口。


2.运用区别

抽象类是对事物整体(属性,行为)的抽象,而接口是对事物局部(行为)的抽象。

举个简单的例子,飞机和鸟是不同类的事物,但是它们都有一个共性,就是都会飞。

在设计的时候,可以将飞机设计为一个类 Airplane,将鸟设计为一个类 Bird。

但是不能将飞行这个特性也设计为类,因此它只是一个行为特性,并不是对一类事物的抽象描述。

此时可以将飞行 设计为一个接口 Fly,包含方法fly( ),然后 Airplane 和 Bird 分别根据自己的需要实现Fly 这个接口。

然后至于有不同种类的飞机,比如战斗机、民用飞机等直接继承 Airplane 即可,对于鸟也是类似的,不同种类的鸟直接继承 Bird 类即可。

从这里可以看出,继承是一个 “是不是”的关系,而接口实现则是 “有没有”的关系。

如果一个类继承了某个抽象类,则子类必定是抽象类的种类,而接口实现则是有没有、具备不具备的关系,比如鸟是否能飞(或者是否具备飞行这个特点),能飞行则可以实现这个接口,不能飞行就不实现这个接口。

 以上就是05.Java 基础 - 接口的内容,更多相关内容请关注PHP中文网(www.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

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

What is the difference between an abstract class and an interface in PHP? What is the difference between an abstract class and an interface in PHP? Apr 08, 2025 am 12:08 AM

The main difference between an abstract class and an interface is that an abstract class can contain the implementation of a method, while an interface can only define the signature of a method. 1. Abstract class is defined using abstract keyword, which can contain abstract and concrete methods, suitable for providing default implementations and shared code. 2. The interface is defined using the interface keyword, which only contains method signatures, which is suitable for defining behavioral norms and multiple inheritance.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles