📜  Java中接口的继承与示例(1)

📅  最后修改于: 2023-12-03 15:31:49.471000             🧑  作者: Mango

Java中接口的继承

在Java中,接口可以像类一样进行继承,这称为接口继承。通过接口继承,一个接口可以获得另一个接口的属性。接口继承可以通过关键字extends完成。

当一个接口从另一个接口继承时,继承了父接口的所有属性(方法名称、方法类型、参数数量和类型),并且可以添加自己的属性。

下面是接口继承的示例代码:

interface Animal {
  public void animalSound(); // interface method (does not have a body)
  public void sleep(); // interface method (does not have a body)
}

// Pig "implements" the Animal interface
class Pig implements Animal {
  public void animalSound() {
    // The body of animalSound() is provided here
    System.out.println("The pig says: wee wee");
  }
  public void sleep() {
    // The body of sleep() is provided here
    System.out.println("Zzz");
  }
}

// Dog "implements" the Animal interface
class Dog implements Animal {
  public void animalSound() {
    // The body of animalSound() is provided here
    System.out.println("The dog says: bow wow");
  }
  public void sleep() {
    // The body of sleep() is provided here
    System.out.println("Zzz");
  }
}

// Main method to execute the code
class Main {
  public static void main(String[] args) {
    Pig myPig = new Pig(); // Create a Pig object
    myPig.animalSound();
    myPig.sleep();

    Dog myDog = new Dog(); // Create a Dog object
    myDog.animalSound();
    myDog.sleep();
  }
}

在上面的示例中,我们定义了一个名为Animal的接口,其中包含animalSound()sleep()方法。然后我们定义了两个类PigDog,它们都实现了Animal接口。这意味着它们都必须覆盖(实现)animalSound()sleep()方法。

最后,我们在main方法中创建了PigDog对象,并调用它们的方法。

接口继承允许我们编写高层代码,从而使我们的代码更加模块化和易于维护。通过将接口分解为更小的、更具体的接口,我们可以将代码分解为更小、更具体的模块,从而更好地组织我们的代码。