interface在java中怎么使用

37次阅读
没有评论

共计 667 个字符,预计需要花费 2 分钟才能阅读完成。

在 Java 中,可以使用关键字 ”interface” 来定义一个接口。接口是一种抽象类型,它只定义了方法的签名和常量的声明,而没有具体实现。
以下是定义一个接口的基本语法:

public interface 接口名称 {
// 声明常量
// 声明方法
}

接口中的常量和方法默认为公共的,无需添加访问修饰符。一个类可以实现(implement)一个或多个接口,实现接口的类需要实现接口中声明的所有方法。
以下是一个简单的示例,展示了如何定义和实现接口:

// 定义一个接口
public interface Animal {
int LEGS = 4; // 接口中的常量
void makeSound(); // 接口中的方法}
// 实现接口
public class Dog implements Animal {
@Override
public void makeSound() {System.out.println("汪汪!");
}
}
public class Main {public static void main(String[] args) {Dog dog = new Dog();
dog.makeSound(); // 输出:"汪汪!"
System.out.println(Animal.LEGS); // 输出:4
}
}

在以上示例中,Animal 是一个接口,其中声明了一个常量 LEGS 和一个方法 makeSound。Dog 类实现了 Animal 接口,并实现了 makeSound 方法。在 Main 类中,我们创建了一个 Dog 对象并调用了 makeSound 方法和访问了 Animal 接口中的常量 LEGS。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-21发表,共计667字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)