为什么我们不能对接口中的方法同时使用默认访问修饰符和抽象关键字?

why cannot we use default access modifier and abstract keyword together for a method in a interface?

我只是想知道为什么我们不能在一个界面中将 default 和 abstract 关键字并排放置?

public 和抽象允许用于一个接口,当涉及到同一个包时,默认是 public 。那么为什么 public abstract 而不是 default abstract 呢?

注意:这是针对java7

的低版本

你好像误解了什么。

在一个接口中,所有没有主体的方法都被认为是抽象方法。

默认方法是 java 8 的新功能,

目的是解决兼容旧java版本的问题,帮助您定义一个默认方法。

无论何时你想使用默认值,你都必须提供一个带有主体实现的方法。

更多信息:http://ocpj8.javastudyguide.com/ch04.html

关键字是互斥的。 JLS 表示:

It is a compile-time error if an interface method declaration has more than one of the keywords abstract, default, or static.

关于关键字 abstractsays:

It is a compile-time error if an interface method declaration is abstract (explicitly or implicitly) and has a block for its body.

但对于带有关键字 default 的方法,它 requires:

Its body is always represented by a block, which provides a default implementation for any class that implements the interface without overriding the method.

总结:

  • 一个abstract方法没有主体
  • 一个default方法提供了一个body

不能同时拥有一个和另一个。

(在Java8之前) 发生的混淆是单词“default”访问修饰符。当没有为方法指定访问修饰符时,它被称为 default 但早期版本 Java 没有这样的术语 8. 我们只是将该方法称为 default 作用域,但访问修饰符没有 default 这样的关键字。

package com.Whosebug;

import java.util.HashMap;

public abstract class Student {

    private String name ;
    private String address;
    private HashMap<Integer, Integer> testMarks;


    public Student(String name,String address) {
        this.name = name;
        this.address = address;
        testMarks.put(1, 0);
        testMarks.put(2, 0);
        testMarks.put(3, 0);

    }

     abstract void def();// no access modifier and hence it is in default state
}

package com.Whosebug.Interface;

import com.Whosebug.Student;

public class anumal extends Student {

    public anumal(String name, String address) {
        super(name, address);
        // TODO Auto-generated constructor stub
    }

    public void def() {
        System.out.println("hi");
    }

}

在上面的例子中,bot 类 在不同的包中,因此我们不能覆盖 def() 方法,因为它不在范围内。