继承 Inheritance
继承是一种由已存在的类型创建一个或多个子类型的机制,即在现有类的基础上构建子类
访问控制符[修饰符]class 类名 extends 父类名{
...
}
子类拥有父类所有属性和方法。
子类不拥有父类的构造器
父类不拥有子类所特有的属性和方法
继承的优点:
可以创建更为特殊的类型
可提高代码的重用性
提高程序的可维护性
继承是一种由已存在的类型创建一个或多个子类型的机制,即在现有类的基础上构建子类
访问控制符[修饰符]class 类名 extends 父类名{
...
}
子类拥有父类所有属性和方法。
子类不拥有父类的构造器
父类不拥有子类所特有的属性和方法
继承的优点:
可以创建更为特殊的类型
可提高代码的重用性
提高程序的可维护性
Employee类
package oop_pro;
public class Employee {
private String name;
private int age;
private double salary=3000.0;
public Employee(){
}
public Employee(String name,int age,double salary){
this.name=name;
this.setAge(age);
this.salary=salary;
}
public double getSalary() {
return salary;
}//获得月薪
public double getMothlyIncome() {
return salary;
}//获得月总收入
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Manager类
package oop_pro;
public class Manager extends Employee{
private double bonus=1500.0;//奖金
public Manager(){
}
public void setBouns(double bouns) {
this.bonus = bonus;
}
public double getBouns() {
return bonus;
}
}
super关键字:
super关键字
super关键字可以显示调用父类的构造器
如果子类想要新建对象,调用父类的无参构造器,而父类没有不带参数的构造器,就可用super显示调用父类的带参数构造器
或者子类的构造函数加上自己的属性,也要用到super关键字
package oop_pro;
public class Manager_super extends Employee{
private double bonus=1500.0;//奖金
public Manager_super(){
}
public Manager_super(String name,int age,double salary,double bonus){
super (name,age,salary);
this.bonus=bonus;
}
public void setBouns(double bouns) {
this.bonus = bonus;
}
public double getBouns() {
return bonus;
}
}
main()函数
package oop_pro;
public class Inheritancetest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Manager m=new Manager();
double sal=m.getSalary();
System.out.print("经理的奖金为"+m.getBouns()+"\n经理的月薪为"+m.getMothlyIncome());
Manager_super m2=new Manager_super("张三",12,3600,1000);
Manager_super m3=new Manager_super("张三",12,3600);//显示错误
}
}
运行结果:
经理的奖金为1500.0
经理的月薪为3000.0
2018年3月23日补充:
public class Person {
String name;
int age;
String address;
Person(){
}
Person(String name,int age,String address){
this.name=name;
this.age=age;
this.address=address;
}
public void zz(){
System.out.println("zz");
}
}
public class Student extends Person{
int number;
// Student(){
//
// }
Student(String name,int age,String address,int number){
super(name,age,address);
this.number=number;
}
public void cc(){
super.zz();//利用super关键字调用父类的方法
}
public void ss(){
this.cc();
}
// public static void ss(){
// super.zz();//静态方法中不能用super和this
// this.cc();
// }
public static void main(String [] args){
// Student b=new Student();//父类有无参的构造函数,子类不能直接用无参的构造函数,必须重新定义
Student a=new Student("name", 10, "address", 001);
a.cc();
a.ss();
}
}
运行结果:
zz
zz