抽象类与接口学习时遇到的问题

抽象一个Person类

package day02;

public abstract class Person {
private String name;
private String ID;

Person(String name,String ID){
this.name=name;
this.ID=ID;
}

abstract void speak();

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getID() {
return ID;
}

public void setID(String iD) {
ID = iD;
}

}
-----------------------------------------
另一个类继承并重写Person类的方法

package day02;

public class PersonImp extends Person {

PersonImp(String name, String ID) {
super(name, ID);
}

@Override

void speak() {


}

}
-----------------------------------------
将继承Person类的子类方法,实例化,并调用

package day02;

public class TestPerson {

public static void main(String[] args) {
PersonImp test = new PersonImp("张三","zs");
String name =test.getName();
String ID=test.getID();
System.out.println(name+"\t"+ID);

}

}
----------------------------------------------
而直接使用接口来写,只能写抽象方法,属性name,ID  必须初始化,所以注意区分   接口与抽象类的作用

package day03;

public interface Person {
//The blank final field ID may not have been initialized
//未初始化空白的最终字段ID
String name;
//The blank final field ID may not have been initialized
//未初始化空白的最终字段ID
String ID;

}

猜你喜欢

转载自www.cnblogs.com/liyunchuan/p/10659543.html