标签:
http://user.qzone.qq.com/1282179846/blog/1470248763
引入一个简单的例子:
//Employee类 import java.util.*; public class Employee { private String name; private double salary; private Date hireday; public Employee(String n,double s,int year,int month,int day) { name =n; salary = s; GregorianCalendar calendar = new GregorianCalendar(year,month-1,day); hireday = calendar.getTime(); } public String getName() { return name; } public double getsalary() { return salary; } public Date gethireday() { return hireday; } public void raisesalary(double bypercent) { double raise = salary*bypercent/100; salary = salary + raise; } //public static void main(String[] args) { //Employee[] staff = new Employee[3]; //staff[0]=new Employee("diyige",75000,1987,12,25); //staff[1]=new Employee("dierge",50000,1989,10,1); //staff[2]= new Employee("disange",40000,1990,3,15); //for(Employee e : staff) //{ // e.raisesalary(5); //} //for(Employee e : staff) //{ // System.out.println("name="+e.getName()+",salary="+e.getsalary()+",hireday="+e.gethireday()); //} //} }
//manager类 public class Manager extends Employee{ private double bonus; public Manager(String n,double s,int year,int month,int day) { super(n,s,year,month,day); bonus = 0; } public void setbonus(double b) { bonus = b; } public double getsalary() { double basesalary = super.getsalary(); return basesalary+bonus; } //public static void main(String[] args) { //} }
//Testmanager public class Testmanager { public static void main(String[] args) { Manager boss = new Manager("bossa",80000,1987,12,15); boss.setbonus(5000); Employee[] staff = new Employee[3]; staff[0]=boss; staff[1]= new Employee("diyige",50000,1989,10,1); staff[2]= new Employee("dierge",40000,1990,3,15); for(Employee e : staff) { System.out.println("name="+e.getName()+",salary="+e.getsalary()); } } }
1/关键字extends表示继承。表明正在构造一个新类派生于一个已经存在的类。已经存在的类称为超类/基类/或者父类;新类称为子类/派生类/或者孩子类。
子类拥有的功能比超类更加的丰富。(是一句废话)
在设计的时候要将通用的方法放在超类中,将具有特殊用途的方法放在子类中。
2/子类要想访问要想访问超类中的方法需要使用特定的关键字super。例如:
public double getsalary() { double basesalary = super.getsalary(); return basesalary+bonus; }
在子类中可以增加域,增加方法,覆盖超类的方法,然而绝对不能删除集成的任何域和方法。
3/上面的代码中,有:
public Manager(String n,double s,int year,int month,int day) { super(n,s,year,month,day); bonus = 0; }
其中
super(n,s,year,month,day);
的意思是调用超类中含有n,s,year,month,day参数的构造器。由于子类的构造器不能访问超类中的私有域,所以必须利用超类中的构造器对这部分的私有域进行初始化,我们可以通过super实现对超类构造器的调用。
super调用构造器的语句必须是子类构造器的第一条语句。
标签:
原文地址:http://www.cnblogs.com/liuxuanqing/p/5739791.html