【JAVA】this和super关键字的用法

一、this关键字的用法

(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;

}

这样做的好处是对于共同部分的构造器代码只需要写一遍即可,其它构造器可直接在其上面进行增添新的内容。

二、super关键字的用法

和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;
}









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值