this
1.this能出现在实例方法和构造方法中
2.this不能使用在静态方法中
3.this大部分情况下可以省略,除了区分局部变量和实例变量时
4.this只能出现在构造器/构造方法第一行
目的是代码复用
super
1.super能出现在实例方法和构造方法中
2.super不能使用在静态方法中
3.super大部分情况下可以省略(系统隐式自动补充在构造方法第一行),除了–父类和子类都有的同名变量/方法,此时需要区分,就不能省略super。此时语法为super.变量名/super.方法名
4.super只能出现构造方法的第一行,通过当前的构造方法调用父类中的构造方法.当一个构造方法第一行既没有this也没有super时(因为this也只能在第一行),默认会有一个 隐藏的super,自动调用父类的无参构造方法,所以任何时候保证父类有一个无参构造方法–由于写了任意的构造方法系统就不会提供默认无参构造方法,所以把无参构造方法自己写出来
super()//调用父类的构造方法
super.变量名//访问父类的变量
super.方法名//访问父类的方法
目的是代码复用,创建子类时,先初始化父类特征,即–无论如何,父类的构造方法都会先执行
先看一段代码
public class test {
public static void main(String[] args) {
new C();
}
}
class A{
public A(){
System.out.println("1");
}
}
class B extends A{
public B(){
System.out.println("2");
}
public B(String name){
//这里有一个看不见的super();
System.out.println("3");
}
}
class C extends B{
public C(){
this("zhangsan");
System.out.println("4");
}
public C(String name){
this(name,20);
System.out.println("5");
}
public C(String name,int age){
super(name);
System.out.println("6");
}
}
上面这代码输出结果是13654
再看一段代码
public class test {
public static void main(String[] args) {
}
}
class Account{
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
private String accountNumber;
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
private double balance;
public Account(){}
public Account(String accountNumber,double balance){
this.accountNumber = accountNumber;
this.balance = balance;
}
}
class CreditAccount extends Account{
public double getCredit() {
return credit;
}
public void setCredit(double credit) {
this.credit = credit;
}
private double credit;
public CreditAccount(){}
}
思考第一个问题,信用账户类中,假使定义一个方法,为
public void dosome(){
System.out.println(accountNumber);
}
编译报错,因为accountNumber是私有变量,子类无法继承私有变量
//修改为System.out.println(getAccountNumber);可正常编译
再看一个代码片段,定义了一个信用账户的有参数构造方法
public CreditAccount(String accountNumeber,double balance,double credit){
this.accountNumber = accountNumber;
this.balance = balance;
this.credit = credit;
}
编译报错,‘accountNumber’ 在 ‘Account’ 中具有 private 访问权限
//修改为以下片段即可正常运行
public CreditAccount(String accountNumeber,double balance,double credit){
super(accountNumeber,balance);
this.credit = credit;
}