接口
理解
- interface
- 实现类似于多继承的效果
语法
public interface 接口名 {
成员常量;
抽象方法;
}
public interface MyInterface {
//public static final double PI = 3.14; 前面三个修饰符重复,接口中默认存在
double PI = 3.14;//常量 的名字应该都是大写
//public abstract void getName(){} 接口中方法默认被 public abstract修饰,没有方法体
void getName();
int test1();
void test2();
}
public interface MyInterface2 {
double E = 2.718;
double sumN();
void printNum();
}
注意:
- 成员常量默认被 public static final 修饰
- 方法默认被 public abstract 修饰
- 类实现了接口必须要实现接口的方法
- 可以有子接口(extends)
实现接口的方法
类的理解
- 使用类去实现接口
- 类的命名规则
- 类名+Impl
- 可以有自己的属性和方法
类的创建
- 方式1
- 使用implements 实现接口 MyInterface
- 重写接口的方法
- 增加了自己的属性及方法
public class MyInterfaceImpl1 implements MyInterface {
private int number;
public MyInterfaceImpl1() {
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
@Override
public void getName() {
}
@Override
public int test1() {
return 0;
}
@Override
public void test2() {
}
}
- 方式2
- 使用extends 继承 MyInterfaceImpl
- 使用implements 实现接口
- 可以再重新写接口的方法,不需要可以用父类的方法
- 可以增加自己的属性和方法
- 借助工具 通过Generate–>Override Method–>选择接口或父类的方法
public class MyInterfaceImpl2 extends MyInterfaceImpl1 implements MyInterface {
public MyInterfaceImpl2() {
super();//父类构造器
}
@Override
public int getNumber() {
return super.getNumber();
}
@Override
public void setNumber(int number) {
super.setNumber(number);
}
@Override
public void getName() {
super.getName();
}
@Override
public void test2(){
System.out.println("重写接口的方法");
}
public void test3(){
System.out.println("MyInterfaceImpl2的方法");
}
}
- 方式3
- 使用extends 继承 MyInterfaceImpl
- 使用implements 实现Myinterface
- 使用implements 实现Myinterface2
- 使用implements 适合4-5个接口
- 可以再重新写接口的方法,不需要可以用父类的方法
- 可以增加自己的属性和方法
- 借助工具 通过Generate–>Override Method–>选择接口或父类的方法
public class Myclass extends MyInterfaceImpl1 implements MyInterface,MyInterface2 {
@Override
public double sumN() {
return 0;
}
@Override
public void printNum() {
}
}
测试
public class Test2 {
public static void main(String[] args) {
MyInterfaceImpl1 m1 = new MyInterfaceImpl1();
m1.test1();//接口实现方法1
m1.test1();//接口实现方法2
MyInterfaceImpl2 m2 = new MyInterfaceImpl2();
m2.test3();//m2 自己的方法3
m2.test1();//m2 接口实现方法1
m2.getNumber();// m2继承父类m1的方法getNumber
Myclass myclass = new Myclass();
myclass.getName();//myclass继承父类m1的方法getNumber
myclass.test1();//接口1 实现方法1
myclass.sumN();//接口2 实现方法sumN()
}
}