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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值