Java interface: definition and implementation of interface, definition and implementation of interface
•
Java
Define interface
public interface A { publicA(){…} // 编译出错,接口不允许定义构造方法 }
public interface StudentInterface extends PeopleInterface { // 接口 StudentInterface 继承 PeopleInterface int age = 25; // 常量age重写父接口中的age常量 void getInfo(); // 方法getInfo()重写父接口中的getInfo()方法 }
[public] interface interface_name [extends interface1_name[,interface2_name,…]] { // 接口体,其中可以包含定义常量和声明方法 [public] [static] [final] type constant_name = value; // 定义常量 [public] [abstract] returnType method_name(parameter_list); // 声明方法 }
public interface MyInterface { // 接口myInterface String name; // 不合法,变量name必须初始化 int age = 20; // 合法,等同于 public static final int age=20; void getInfo(); // 方法声明,等同于 public abstract void getInfo(); }
Implementation interface
<public> class <class_name> [extends superclass_name] [implements interface[,interface…]] { //主体 }
Example 1
public interface IMath { public int sum(); // 完成两个数的相加 public int maxNum(int a,int b); // 获取较大的数 }
public class MathClass implements IMath { private int num1; // 第 1 个操作数 private int num2; // 第 2 个操作数 public MathClass(int num1,int num2) { // 构造方法 this.num1 = num1; this.num2 = num2; } // 实现接口中的求和方法 public int sum() { return num1 + num2; } // 实现接口中的获取较大数的方法 public int maxNum(int a,int b) { if(a >= b) { return a; } else { return b; } } }
public class NumTest { public static void main(String[] args) { // 创建实现类的对象 MathClass calc = new MathClass(100,300); System.out.println("100 和 300 相加结果是:" + calc.sum()); System.out.println("100 比较 300,哪个大:" + calc.maxNum(100,300)); } }
100 和 300 相加结果是:400 100 比较 300,哪个大:300
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码