Java学习

接口

接口通过interface来定义,其中可以包含一些常量和方法

特征

  1. 接口中定义的变量会在编译的时候自动加上public static final修饰符,意味着该“变量”其实是常量,所以其值无法改变
  2. 没有private、default、static修饰的方法是隐式抽象的,也就是其在编译时会自动加上public abstract修饰符
  3. 接口中允许定义静态方法和default方法
  4. 接口不允许直接实例化,需要定义一个类去实现接口
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
//定义接口
interface Person{
//常量
int CLASS = 1;

//抽象方法
int getGrades();

//静态方法
static boolean isClass(int c)
{
return c==CLASS;
}

//默认方法
default void printDescripton(){
System.out.println("班级");
}
}

//接口的实现
public class Bao implements Person{
@Override
public int getGrades()
{
return 100;
}

public static void main(String[] args)
{
new Bao();
}
}
  1. 接口可以是空的(作为标记型接口使用)

作用

  1. 使某些实现类具有我们想要的功能。例如实现了Cloneable接口(标记行接口,内部是空的)的类可以使用Object.clone()方法,否则会抛出CloneNotSupportedException
  2. Java原则上只支持单一继承,通过接口可以实现多重继承的目的
  3. 实现多态
    多态指的是同一个事件发生在不同的对象上会产生不同的结果
  • 多态存在的前提
    • 有继承关系
    • 子类重写父类的方法
    • 父类引用指向子类对象
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
39
40
41
42
43
44
import java.util.ArrayList;
import java.util.List;

interface Shape{
String name();
}

//有继承关系
class Circle implements Shape{
//子类重写父类方法
@Override
public String name()
{
return "圆";
}
}

class Square implements Shape{
@Override
public String name()
{
return "正方形";
}
}

public class Main{
public static void main(String[] args)
{
List<Shape> shapes = new ArrayList<>();

//父类引用指向子类对象
Shape circle = new Circle();
Shape square = new Square();

shapes.add(circle);
shapes.add(square);

for(Shape shape:shapes)
{
System.out.println(shape.name());
}
}

}