一、this关键字的用法
二、super关键字的用法(1)引用隐式参数
在类的构造器中如果实例域名与显示参数名相同时,可以用this引用隐式参数以区分开。如下这段代码
class Employee { public Employee(String name, double salary) { this.name = name; this.salary = salary; } private String name; private double salary; }
实例域name和salary与显示参数重名,为了区分可以加上this引用隐式参数(2)调用该类的其它构造器
如果构造器的第一条语句形如this(...),这个构造器将调用该类的另一个构造器。请看下面这段代码
class Employee { public Employee(String name, double salary) { this.name = name; this.salary = salary; } public Employee(double s) { //calls Employee(String, double) this("Employee #"+id,s); id++; } private String name; private double salary; }
这样做的好处是对于共同部分的构造器代码只需要写一遍即可,其它构造器可直接在其上面进行增添新的内容。
和this关键字很类似,super也有两个用法,而且与this基本也是对应的,掌握了this理解super会容易很多。
(1)调用超类的方法
这出现在类的继承中,如果子类某一个方法覆盖掉了超类的方法,如果在子类中直接调用只能调用子类的方法,这时如果想调用超类的同名方法就要使用super关键字
(2)调用超类的构造器
具体例子请看如下代码
class Employee { public Employee(String n, double s, int year, int month, int day) { name = n; salary = s; GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day); // GregorianCalendar uses 0 for January 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 += raise; } private String name; private double salary; private Date hireDay; } class Manager extends Employee { /** @param n the employee's name @param s the salary @param year the hire year @param month the hire month @param day the hire day */ public Manager(String n, double s, int year, int month, int day) { super(n, s, year, month, day); bonus = 0; } public double getSalary() { double baseSalary = super.getSalary(); return baseSalary + bonus; } public void setBonus(double b) { bonus = b; } private double bonus; }