【问题标题】:What is wrong with this interface? [duplicate]这个界面有什么问题? [复制]
【发布时间】:2021-04-04 15:51:53
【问题描述】:

接口可以包含正文吗?帮我解决这部分

public interface Figures
{
  public void printMessage (String s)
  {
    System.out.println ("This figure is " + s);
  }
  public double area ();    // to calculate the area of the figure
}

【问题讨论】:

  • 不,接口不能包含方法体。如果必须这样做,请使用default。
  • 如何使用它给我sn-p pls
  • @AMohamedSakeel 做这个公共默认 void printMessage(String s)
  • @markspace 你自相矛盾。如果使用default,接口可以包含方法体。

标签: java interface abstract


【解决方案1】:

接口是一个完全“抽象的类”,用于将相关方法与空体进行分组

public interface Figures
{
  public void printMessage (String s);
  public double area ();    // to calculate the area of the figure
}

要访问接口方法,接口必须由另一个类使用 implements 关键字(而不是扩展)“实现”(有点像继承)。接口方法的主体由“实现”类提供。

here 解释清楚

这是w3school的例子

// Interface
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");
  }
}

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

【讨论】:

  • 那么,在哪里打印输出
  • 在实现你的接口的类中
  • 从 Java 8 开始,有一些默认方法允许您在接口内提供接口方法的默认实现。
【解决方案2】:

从 Java 8 开始,我们可以使用 default 关键字为接口方法提供默认植入

public interface Figures
{
  public default void printMessage (String s)
  {
    System.out.println ("This figure is " + s);
  }
  public double area ();    // to calculate the area of the figure
}

【讨论】:

  • 这是标准方法而不是实现
  • 你说的标准方法是什么意思?
  • 接口可以实现吗?
  • 从 Java 8 开始是的 :)
  • 我需要使用Implement类而不是Default
猜你喜欢
  • 2020-06-17
  • 1970-01-01
  • 2011-02-06
  • 2013-06-15
  • 2018-04-06
  • 2016-08-03
  • 1970-01-01
相关资源
最近更新 更多