抽象类
abstract面向抽象编程
abstract......是标准
public abstract void move();
//抽象方法没有方法体
//public void test();
//这个不是抽象方法,抽象方法要被abstract修饰,且没有方法体,即没有花括号{}。
接口类型
单一性原则
解耦合,高内聚
在类的继承中,只能做单重继承,而实现接口时,一次则可以实现多个接口,每个接口间使用逗号隔开。
只有接口可以多继承
想要实现某个接口,一定要重写该接口的方法。
public abstract class Animal{
//不能实例化,有构造方法
//默认无参,无参构造一定要显式定义
public Animal(){}
/*
private int id;
public Animal (int id){
this.id = id;
}
*/
}
class Dog extends Animal{
public Dog(){
super();
}
/*
public Dog(int id){
super(id);
//父类的无参构造
}
*/
}
class Test{
public static void main(String[] args){
Dog d = new Dog();
//Dog d = new Dog(10);
System.out.println(id);
}
}
接口里可以定义字段,可以定义静态方法,但不能实现
public interface USB{
//接口是抽象方法的集合
void move();
void eat(String food,String foodName);
default void test(){
System.out.println("Hello");
}
static void a(){
System.out.println("hello");
}
}
public class Main{
public static void main(String[] args){
USB.a();
MyUSB.myUSB = new MyUSB();
myUSB.eat("电","万伏高压电");
}
}
class MyUSB implements USB{
public void move(){}
public void eat(String food,String foodName){
System.out.println(food+" "+foodName);
}
}