Java继承思想的实现

//父类
public class Employee {
    private String name;  //姓名
    private int age;      //年龄
    private double salary = 2000.0;//薪水
    public Employee(String name,int age,double salary){
        this.name = name;
        this.age = age;
        this.salary = salary;
    }
    public Employee(){}

    public double getSalary() {
        return salary;
    }
}
//子类
public class Mannager extends Employee {   //经理类继承自员工类
    private double bonus ;//奖金

    public void setBonus(double bonus) {
        this.bonus = bonus;
    }
}
//测试类
public class TestInheritance {
    public static void main(String args[]){
        Mannager mannager = new Mannager();
        double sal = mannager.getSalary();
        System.out.println("继承的薪水为:"+sal);

    }
}

运行结果为:

继承的薪水为:2000.0

注意:

1.子类不能继承父类的构造方法,因为父类的构造方法是专门用来构造父类的模板,而不能构造子类。
2.父类的私有属性或方法虽被继承,但子类却无法访问。
3.子类构造方法中调用父类的构造方法的语法为:super()或者是super(实参列表)
4.子类构造方法中调用父类的普通方法的语法为:super.methodname()或者是super.methodname(实参列表)。

猜你喜欢

转载自blog.csdn.net/gfjserhukher/article/details/82559071