接口,抽象

  • interface(接口)和 abstract(抽象)都是为了做一件事,那就是将方法与方法体(实现)分离。有什么实际意义,分工合作吧。
  • 但是又有自己的特点,不然就叫一个名得了。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    public abstract class  Calculate {
    double num1;
    double num2;
    public abstract void add(double num1,double num2);
    public abstract void sub(double num1,double num2);
    public abstract void mul(double num1,double num2);
    public abstract void div(double num1,double num2);
    public abstract void mod(double num1,double num2);
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public  class Method extends Calculate{
public void add(double num1,double num2) {
System.out.println(num1+num2);
}
public void sub(double num1,double num2){
System.out.println(num1-num2);
}
public void mul(double num1,double num2){
System.out.println(num1*num2);
}
public void div(double num1,double num2){
System.out.println(num1/num2);
}
public void mod(double num1,double num2){
System.out.println(num1%num2);
}
}

抽象类不能实例化为对象,但是被继承后就好说话了,继承后的类就和普通的类一样了,可以实例化。然后调用这些方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.Scanner;
public class Cal {
public static void main(String[] args) {
Method method = new Method();
double num1=0,num2=0;
int choose=1;
for(;;) {
try {
Scanner scanner = new Scanner(System.in);
System.out.println("输入第一个数值");
num1 = scanner.nextDouble();
System.out.println("输入第二个数值");
num2 = scanner.nextDouble();
System.out.println("1.+ 2.- 3.* 4./ 5%");
choose = scanner.nextInt();
} catch (Exception e) {
System.out.println("输入不正确");
}
switch (choose) {
case 1:
method.add(num1, num2);
break;
case 2:
method.sub(num1, num2);
break;
case 3:
method.mul(num1, num2);
break;
case 4:
method.div(num1, num2);
break;
case 5:
method.mod(num1, num2);
break;
}
}
}
}

接口?差不多。区别就这么点

1
interface Calculate {方法名}
1
public class Method implements Calculate{方法体}

不过,抽象类里还可以有自己的方法体,而接口就纯接口,抽象类只能被一个继承,而接口可以被很多去实现。

快下课了,回去了!