抽象类
1.关键字:abstract
像这种没有实际工作的方法, 我们可以把它设计成一个 抽象方法(abstract method), 包含抽象方法的类我们称为 抽象类(abstract class).
abstract class Shape {
abstract public void draw();
}
2.注意事项: 抽象类不能直接实例化.
抽象方法不能是 private 的
抽象类中可以包含其他的非抽象方法, 也可以包含字段. 这个非抽象方法和普通方法的规则都是一样的,可以被重写,也可以被子类直接调用
abstract class Shape {
abstract public void draw();
void func() {
System.out.println("func");
}
}
class Rect extends Shape {
...
}
public class Test {
public static void main(String[] args) {
Shape shape = new Rect();
shape.func();
}
}
// 执行结果
func
3.抽象类存在的最大意义就是为了被继承,抽象类相当于多了一重编译器的校验
4.抽象类被继承后一定要重写抽象方法,如果抽象类继承抽象类则可以不用重写
接口
1.关键字 interface
2.接口是抽象类的更进一步. 抽象类中还可以包含非抽象方法, 和字段. 而接口中包含的方法都是抽象方法, 字段只能包含静态常量.
3.接口中的方法都不能具体实现,都是抽象方法—默认的public abstract
4.接口中的成员变量默认都是public static final
5.接口不可以直接实例化,我们创建接口的时候, 接口的命名一般以大写字母 I 开头,接口的命名一般使用 “形容词” 词性的单词, 阿里编码规范中约定, 接口中的方法和属性不要加任何修饰符号, 保持代码的简洁性接口中的方法尽量简洁
6.关键字:implements 实现 类implements接口 接口当中的方法必须重写(普通类必须重写,抽象类可以不用)也可以发生向上转型
interface IShape {
void draw();
}
class Cycle implements IShape {
@Override
public void draw() {
System.out.println("○");
}
}
public class Test {
public static void main(String[] args) {
IShape shape = new Rect();
shape.draw();
}
}
7.接口可以多实现,继承只能单继承 类跟接口是实现,接口跟接口是继承,接口可以多个继承extends
class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
}
interface IFlying {
void fly();
}
interface IRunning {
void run();
}
interface ISwimming {
void swim();
}
class Fish extends Animal implements ISwimming {
public Fish(String name) {
super(name);
}
@Override
public void swim() {
System.out.println(this.name + "正在用尾巴游泳");
}
}
class Duck extends Animal implements IRunning, ISwimming, IFlying {
public Duck(String name) {
super(name);
}
@Override
public void fly() {
System.out.println(this.name + "正在用翅膀飞");
}
@Override
public void run() {
System.out.println(this.name + "正在用两条腿跑");
}
@Override
public void swim() {
System.out.println(this.name + "正在漂在水上");
}
}
8.接口间继承
interface IRunning {
void run();
}
interface ISwimming {
void swim();
}
// 两栖的动物, 既能跑, 也能游
interface IAmphibious extends IRunning, ISwimming {
}
class Frog implements IAmphibious {
...
}
总结: