📅  最后修改于: 2020-10-13 03:31:29             🧑  作者: Mango
Java提供了一种在接口内部创建默认方法的功能。在接口内部定义并带有默认标记的方法称为默认方法。这些方法是非抽象方法。
在下面的示例中,Sayable是一个功能接口,其中包含默认值和抽象方法。默认方法的概念用于定义具有默认实现的方法。您还可以覆盖默认方法,以为该方法提供更具体的实现。
让我们看一个简单的
interface Sayable{
// Default method
default void say(){
System.out.println("Hello, this is default method");
}
// Abstract method
void sayMore(String msg);
}
public class DefaultMethods implements Sayable{
public void sayMore(String msg){// implementing abstract method
System.out.println(msg);
}
public static void main(String[] args) {
DefaultMethods dm = new DefaultMethods();
dm.say();// calling default method
dm.sayMore("Work is worship");// calling abstract method
}
}
输出:
Hello, this is default method
Work is worship
您还可以在接口内定义静态方法。静态方法用于定义实用程序方法。下面的例子说明,如何在接口中实现静态方法?
interface Sayable{
// default method
default void say(){
System.out.println("Hello, this is default method");
}
// Abstract method
void sayMore(String msg);
// static method
static void sayLouder(String msg){
System.out.println(msg);
}
}
public class DefaultMethods implements Sayable{
public void sayMore(String msg){ // implementing abstract method
System.out.println(msg);
}
public static void main(String[] args) {
DefaultMethods dm = new DefaultMethods();
dm.say(); // calling default method
dm.sayMore("Work is worship"); // calling abstract method
Sayable.sayLouder("Helloooo..."); // calling static method
}
}
输出:
Hello there
Work is worship
Helloooo...
在接口中具有默认和静态方法之后,我们考虑Java中抽象类的需求。接口和抽象类几乎相似,除了可以在抽象类中创建构造函数,而不能在接口中创建构造函数。
abstract class AbstractClass{
public AbstractClass() { // constructor
System.out.println("You can create constructor in abstract class");
}
abstract int add(int a, int b); // abstract method
int sub(int a, int b){ // non-abstract method
return a-b;
}
static int multiply(int a, int b){ // static method
return a*b;
}
}
public class AbstractTest extends AbstractClass{
public int add(int a, int b){ // implementing abstract method
return a+b;
}
public static void main(String[] args) {
AbstractTest a = new AbstractTest();
int result1 = a.add(20, 10); // calling abstract method
int result2 = a.sub(20, 10); // calling non-abstract method
int result3 = AbstractClass.multiply(20, 10); // calling static method
System.out.println("Addition: "+result1);
System.out.println("Substraction: "+result2);
System.out.println("Multiplication: "+result3);
}
}
输出:
You can create constructor in abstract class
Addition: 30
Substraction: 10
Multiplication: 200