本文重点介绍 Java 中类和接口之间的区别。它们在语法上看起来很相似,都包含方法和变量,但它们在很多方面都不同。

类是用户定义的蓝图或原型,从中创建对象。它表示一种类型的所有对象共有的一组属性或方法。一般来说,类声明可以包括这些组件,按顺序:

  • 修饰符:类可以是公共的或具有默认访问权限。
  • 类名:名称应以首字母开头(按约定大写)。
  • 超类(如果有):类的父类(超类)的名称(如果有),前面有关键字 extends。一个类只能扩展(子类)一个父类。
  • 接口(如果有):由类实现的接口的逗号分隔列表,如果有的话,前面有关键字 implements。一个类可以实现多个接口。
  • 类主体:用大括号 { } 包围的类主体。
  • 构造函数用于初始化新对象。字段是提供类及其对象状态的变量,方法用于实现类及其对象的行为。

例子:

// Java program to demonstrate Class

// Class Declaration
public class Dog {

    // Instance Variables
    String name;
    String breed;
    int age;
    String color;

    // Constructor Declaration of Class
    public Dog(String name, String breed,
            int age, String color)
    {
        this.name = name;
        this.breed = breed;
        this.age = age;
        this.color = color;
    }

    // method 1
    public String getName()
    {
        return name;
    }

    // method 2
    public String getBreed()
    {
        return breed;
    }

    // method 3
    public int getAge()
    {
        return age;
    }

    // method 4
    public String getColor()
    {
        return color;
    }

    @Override
    public String toString()
    {
        return ("Hi my name is " + this.getName() + " My breed, age and color are " + this.getBreed() + ", " + this.getAge() + ", " + this.getColor());
    }

    public static void main(String[] args)
    {
        Dog pipi = new Dog("Pipi", "papillon", 5, "white");
        System.out.println(pipi.toString());
    }
}

运行结果:

Hi my name is Pipi.
My breed, age and color are papillon, 5, white

接口

和类一样,接口可以有方法和变量,但是接口中声明的方法默认是抽象的(只有方法签名,没有主体)。

  • 接口指定一个类必须做什么而不是如何做,这是类的蓝图。
  • 接口是关于能力的,比如 Player 可能是一个接口,任何实现 Player 的类都必须能够(或必须实现)move()。所以它指定了类必须实现的一组方法。
  • 如果一个类实现了一个接口并且没有为接口中指定的所有函数提供方法体,那么类必须被声明为抽象的。
  • Java 库示例是比较器接口。如果一个类实现了这个接口,那么它就可以用来对集合进行排序。

语法:

interface <interface_name> {

    // declare constant fields
    // declare methods that abstract 
    // by default.
}

示例:

// Java program to demonstrate
// working of interface.

import java.io.*;

// A simple interface
interface in1 {

    // public, static and final
    final int a = 10;

    // public and abstract
    void display();
}

// A class that implements the interface.
class testClass implements in1 {

    // Implementing the capabilities of
    // interface.
    public void display()
    {
        System.out.println("Geek");
    }

    // Driver Code
    public static void main(String[] args)
    {
        testClass t = new testClass();
        t.display();
        System.out.println(a);
    }
}

运行结果:

Geek
10

类和接口的对比和区别

接口
用于创建类的关键字是class 用于创建接口的关键字是interface
可以实例化一个类,即可以创建一个类的对象。 无法实例化接口,即无法创建对象。
类不支持多重继承 接口支持多重继承
类可以继承另一个类 接口不能继承一个类
类可以被另一个类使用关键字extends继承 它可以使用关键字implements由类继承,也可以使用关键字extends由接口继承
类可以包含构造函数 接口不能包含构造函数
类不能包含抽象方法 接口仅包含抽象方法
类中的变量和方法可以使用任何访问说明符(publicprivatedefaultprotected) 声明接口中的所有变量和方法都声明为public
类中的变量可以是静态的、最终的或两者都不是。 所有变量都是静态的和最终的。