abstract关键字

  1. 场景分析
  2. Demo

场景分析

abstract关键字只能用于修饰方法和类,无法修饰属性字段。

下面是常见的多态案例,就是通过Override复写父类的run方法,这样同一个run方法有多种实现就叫多态。

class Person {
    protected String name;

    public Person(String name){
        this.name=name;
    }

    public void introduce(){
        System.out.println("I am s Person,name is " + this.name);
    }
}

class Student extends Person {
    private int score;

    public Student(String name,int score){
        super(name);
        this.score=score;
    }

    @Override
    public void introduce() {
        System.out.println("I am s Student,name is " + this.name+", my score is "+this.score);
    }
}

class Teacher extends Person {
    private int salary;

    public Teacher(String name,int salary){
        super(name);
        this.salary = salary;
    }

    @Override
    public void introduce() {
        System.out.println("I am s Teacher,name is " + this.name+", my salary is "+this.salary);
    }
}

public class Hello {
    public static void main(String[] args) {
        Person s1 = new Student("小明",90);
        Person t1 = new Teacher("林老师",6000);

        s1.introduce();   //   I am s Student,name is 小明, my score is 90
        t1.introduce();   //   I am s Teacher,name is 林老师, my salary is 6000
    }
}

可以看到子类不管是Student还是Teacher,都对复写了run方法的实现代码,那么Person类的实现代码就是多余的,因为最后都会被复写。

Person的run()方法没有实际意义,但是不能去掉方法的实现代码。因为我们在定义方法的时候必须实现方法的语句,否则会导致编译错误(除了接口和抽象类里定义方法)。

不管是Student类还是Teacher类,如果都继承于同一父类,那么它们的实例我们统一用高层的父类去接受,这样写是比较好的习惯。

Demo

如果父类中方法的实现代码没有实际意义,因为子类一定会对方法进行复写。这时可以把父类中的方法定义为抽象方法,方法被abstract关键字修饰,那么所在的类也必须声明为抽象类。
抽象类无法被实例化,也就是 new Person() 是不可以的。

概括起来就是在父类中定义抽象方法,父类是抽象类。由于抽象类无法被实例化,所以强制子类去实现抽象父类中的抽象方法,我们是通过子类的实例去调用。

abstract class Person {
    protected String name;

    public Person(String name){
        this.name=name;
    }

    public abstract void introduce();
}

class Student extends Person {
    private int score;

    public Student(String name,int score){
        super(name);
        this.score=score;
    }

    @Override
    public void introduce() {
        System.out.println("I am s Student,name is " + this.name+", my score is "+this.score);
    }
}

class Teacher extends Person {
    private int salary;

    public Teacher(String name,int salary){
        super(name);
        this.salary = salary;
    }

    @Override
    public void introduce() {
        System.out.println("I am s Teacher,name is " + this.name+", my salary is "+this.salary);
    }
}

public class Hello {
    public static void main(String[] args) {
        Person s1 = new Student("小明",90);
        Person t1 = new Teacher("林老师",6000);

        s1.introduce();   //   I am s Student,name is 小明, my score is 90
        t1.introduce();   //   I am s Teacher,name is 林老师, my salary is 6000
    }
}

他の者にできたか?ここまでやれたか?この先できるか?いいや、仆にしかできない!

目录
×

喜欢就点赞,疼爱就打赏