Java-this和super

首先,this代表自身对象的引用,是一个地址。super是一个关键字,不能将super 赋给另一个对象变量,它只是一个指示编译器调用超类方法的特殊关键字。

this作用
  • 引用隐式参数。
  • 调用该类其他的构造器,此时必须这条语句必须是第一条语句。当类没有提供任何构造器的时候,系统才会提供一个默认的构造器。这个构造器将实例域设置为默认值。如果类中提供了至少一个构造器,系统不会提供默认的构造器。
class A{
    public A(){
        System.out.println("father class!");
    }
}
class B extends A{
    private String s;
    public B(){
        System.out.println("sub class not parameters");
    }
    public B(String s){
        this(); //调用无参数的B类构造器,必须放在第一条语句。
        this.s=s;//形参与成员名字重名,用this来区分,this表示隐式参数
        System.out.println("sub class with String parameters "+s);
    }
}
public class Outer {
    public static void main(String args[]){
        B b=new B("Hello world!");
    }

}
super关键字
  • 调用超类的方法。
  • 调用超类的构造器。如果子类的构造器没有显式地调用超类的构造器,则将自动地调用超类默认(没有参数)的构造器
  • 调用超类构造器的语句只能作为另一个构造器的第一条语句出现。
  • this()super() 不能同时出现在一个构造函数里面。
  • this()super() 都不能在static 环境中使用,包括static 变量,static 方法,static 块。
class A{
    public A(){
        System.out.println("father class!");
    }
    void display(){
        System.out.println("display of father class!");
    }
}
class B extends A{
    private String s;
    public B(){
        System.out.println("sub class not parameters");
    }
    public B(String s){
        super(); //调用父类A的构造器,必须是子类构造器的第一条语句。
        super.display(); //调用父类的display方法
        display(); //本类的display()
        System.out.println("sub class with String parameters "+s);
    }
    void display(){ //重写的display
        System.out.println("display of sub class!");
    }
}
public class Outer {
    public static void main(String args[]){
        B b=new B("Hello world!");
    }
}

输出结果:

father class!
display of father class!
display of sub class!
sub class with String parameters Hello world!

如有错误,欢迎留言指正!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值