抽象类(abstract class)与抽象方法

package cm.aff.abst;
/*
 abstract:抽象的,,可以修饰类,方法
 1.修饰类: 抽象类:
                 ①不能被实例化
                 ②有构造器的
                 ③凡是类都有构造器
                 ④抽象方法所修饰的类一定是抽象类
                 ⑤抽象类中可以没有抽象方法
⑥不能用abstract修饰属性,私有方法,构造器,静态方法,final的方法 2.修饰方法:抽象方法: ①格式:没有方法体, 包括{ }.如: public abstract void eat(); ②抽象方法只保留方法的功能,而具体的执行,交给继承抽象类的子类,由子类重写此抽象方法 ③若子类继承抽象类,并重写了所有的抽象方法,则此类是一个 "实体类" ,即可以被实例化 ④若子类继承抽象类,没有重写所有的抽象方法,意味着此类中仍有抽象方法,则此类必须声明为抽象的
*/ public class TestAbstract { public static void main(String[] args) { //Person p1 = new Person();//不能被实例化 //p1.eat(); Student s = new Student(); s.eat(); Person p = new Worker();//多态 p.eat(); } } abstract class Person { String name; public Person(){ } public Person(String name){ this.name = name; } public abstract void eat(); //方法中的语句不能被执行了,里面的语句不要了 //给他一个abstract标识,保留了功能,但没有具体的实现, 得由子类来实现了 public abstract void walk() ; } class Student extends Person { public void eat() { System.out.println("学生吃饭"); } public void walk() { System.out.println("学会走路"); } } class Worker extends Person { public void eat() { System.out.println("工人吃饭"); } public void walk() { System.out.println("工人走路"); } }
输出结果:

学生吃饭
工人吃饭

使用练习:

package cm.aff.abst;

public class TestEmployee {
public static void main(String[] args) {
    //Manager m =  new Manager();
    Employee e1 = new Manager();//使用多态  虚拟方法调用,和上面一样效果
    e1.work();
    
    Employee e2 = new     CommonEmployee(); 
    e2.work();
   }
}

  abstract class   Employee{
      private  String name;
      private int id ;
      private double salary;
      public abstract void work();
      
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
  }
  
    class Manager extends Employee{
        private double bonus;
        public void work(){
            System.out.println("监督工作,提高效率");
        }
        public double getBonus() {
            return bonus;
        }
        public void setBonus(double bonus) {
            this.bonus = bonus;
        }
    }
    
    class CommonEmployee extends Employee{
        public void work(){
            System.out.println("流水线工作");
        }
    }
输出结果:

  监督工作,提高效率
  流水线工作

All that work will definitely pay off
原文地址:https://www.cnblogs.com/afangfang/p/12567545.html