1. 程式人生 > >Java學習筆記之抽象類基本概念(1)

Java學習筆記之抽象類基本概念(1)

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