Java学习
接口
接口通过interface来定义,其中可以包含一些常量和方法
特征
- 接口中定义的变量会在编译的时候自动加上
public static final修饰符,意味着该“变量”其实是常量,所以其值无法改变
- 没有private、default、static修饰的方法是隐式抽象的,也就是其在编译时会自动加上
public abstract修饰符
- 接口中允许定义静态方法和default方法
- 接口不允许直接实例化,需要定义一个类去实现接口
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(); } }
|
- 接口可以是空的(作为标记型接口使用)
作用
- 使某些实现类具有我们想要的功能。例如实现了Cloneable接口(标记行接口,内部是空的)的类可以使用
Object.clone()方法,否则会抛出CloneNotSupportedException
- Java原则上只支持单一继承,通过接口可以实现多重继承的目的
- 实现多态
多态指的是同一个事件发生在不同的对象上会产生不同的结果
- 多态存在的前提
- 有继承关系
- 子类重写父类的方法
- 父类引用指向子类对象
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()); } } }
|