Java学习笔记:类的继承与抽象(抽象类存疑)

来源:互联网 发布:p站搜图软件 编辑:程序博客网 时间:2024/05/22 07:03

继承简单示例

/**java支持单继承与多重继承*/public class ExtendsDemo{public static void main(String[] args){Student stu1=new Student();Baby baby1=new Baby();stu1.name="123";stu1.age=21;stu1.study();baby1.cry();}}class Person{String name="XXX";int age=0;}class Student extends Person{public void study(){System.out.println("name:"+this.name);System.out.println("age:"+this.age);System.out.println("...reading...");}}//当父子类出现同名变量时,用super来区分//super实质为父类空间,存放在子类中class Baby extends Person{String name="789";int age=1;//这种写法仅为演示super的用法,实际上父子类不应出现同名变量public void cry(){System.out.println("name:"+this.name);System.out.println("age:"+super.age);//此处若无super关键字,当父类权限不大于子类时,子类会覆盖父类System.out.println("...crying...");}}

继承中的细节(覆盖,父子类的构造函数)

public class ExtendsDemo{public static void main(String[] args){//继承中子类覆盖父类常用于软件的更新Parent phone1=new Parent();phone1.show();Son phone2=new Son(1);phone2.show();}}class Parent{Parent(){System.out.print("the constructor of parent without param\n");}Parent(int x){System.out.print("the constructor of parent with param\n");}void show(){System.out.print("the old text\n");}}class Son extends Parent{/*子类在构造对象时会默认调用父类的空参数构造函数,因为子类会继承父类的内容,在使用这些内容之前,必须要看父类对这些内容是怎样初始化的若子类构造函数第一行有this(),则不调用super()*/Son(){//super();//此句为继承中子类的隐藏语句,当父类的构造函数含传入参数时,此句需显式写出并表明参数System.out.print("the constructor of son without param\n");}Son(int x){//super();//此句为继承中子类的隐藏语句,当父类的构造函数含传入参数时,此句需显式写出并表明参数super(x);System.out.print("the constructor of son with param\n");}void show(){super.show();System.out.print("added text\n");}}

抽象类示例

//抽象类是指其中成员变量或成员函数不明确的类abstract class Employee{private String name;private int age;private String id;private double salary;Employee(String name,int age,String id,double salary){this.name=name;this.age=age;this.id=id;this.salary=salary;}void ShowInfo(){System.out.println("name:\t"+name);System.out.println("age:\t"+age);System.out.println("id:\t"+id);System.out.println("salary:\t"+salary);}abstract void Work();//根据不同子类而不明确的函数}class Programmer extends Employee{Programmer(String name,int age,String id,double salary){super(name,age,id,salary);}void ShowInfo(){super.ShowInfo();}void Work(){System.out.println("coding");}}class Manager extends Employee{private double bonus;Manager(String name,int age,String id,double salary,double bonus){super(name,age,id,salary);this.bonus=bonus;}void ShowInfo(){super.ShowInfo();System.out.println("bonus:\t"+bonus);}void Work(){System.out.println("managing");}}public class AbstractDemo{public static void main(String[] args){Programmer person1=new Programmer("daya1",21,"A-42",12000);person1.ShowInfo();person1.Work();Manager person2=new Manager("daya2",34,"C-02",16000,3000);person2.ShowInfo();person2.Work();}}
疑惑:在上述抽象类Employee中的抽象函数Work()好像没有存在的必要,这个函数可直接在各子类Programmer与Manager中定义即可。这样便可把Employee变为非抽象类(把抽象函数的声明删掉),由于此段代码是由某视频教程改编而来,不太明白为什么要把Employee弄成抽象类。