1、基本概念
抽象类:包含一个抽象方法的类
抽象方法:用abstract关键字声明,且只有方法名没有方法体的方法。
1.1 抽象类的定义和使用规则
- 包含了一个抽象方法的类必须是抽象类
- 抽象类和抽象方法都要用abstract关键字声明
- 抽象方法只需要声明不用实现
- 抽象类必须被子类继承,子类必须覆写抽象类里的所有抽象方法
abstract class A{ // 抽象类A
private static final String FALG = "CHINA"; // 全局常量
private String name = "YHL";
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public abstract void print(); // 定义抽象方法
}
public class AbstractDemo {
public static void main(String[] args) {
A a = new A(); // 抽象类不能直接实例化
}
}
抽象类必须有子类,而且子类必须覆写抽象类里的全部抽象方法
abstract class A{
private static final String FALG = "CHINA"; // 全局常量
private String name = "YHL";
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public abstract void print(); // 定义抽象方法
}
class B extends A{
public void print(){
System.out.println("重写print方法");
System.out.println("姓名:" + super.getName());
}
}
public class AbstractDemo {
public static void main(String[] args) {
B b = new B();
b.print();
}
}
1.2 一点思考
1、抽象类可以用final关键字声明吗?
当然不可以,final关键字声明的类不能被继承,而抽象类必须被子类继承,抽象方法由子类全部覆写。
2、抽象类能不能定义构造方法
可以,因为抽象类必须被子类继承,而在子类实例化的时候,会先调用父类的构造方法。
abstract class A{
private String name;
private int age;
public A(String name,int age){
this.setName(name);
this.setAge(age);
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setAge(int age){
this.age = age;
}
public int getAge() {
return age;
}
public abstract void getInfo(); // 定义抽象方法
}
class B extends A{
private String school;
public B(String name, int age, String school){
super(name,age);
this.setSchool(school);
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
public void getInfo(){
System.out.println("重写getInfo方法");
System.out.println("姓名:" + super.getName() + " 年龄:" + super.getAge() + " 学校:" + this.getSchool());
}
}
public class AbstractDemo {
public static void main(String[] args) {
B b = new B("zhangsan",20,"NKU");
b.getInfo();
}
}
// 运行结果
重写getInfo方法
姓名:zhangsan 年龄:20 学校:NKU