• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
xiaoyaovo
博客园    首页    新随笔    联系   管理    订阅  订阅
super 和 this 的异同

目录

    • 异同
      • super
      • this
    • 代码示例
      • super
      • this

赶时间的看总结就好了。

异同

super

  • super();调用父类构造方法;
  • super.date; 调用父类的属性;
  • super.func(); 调用父类的方法。

this

  • this();调用构造方法
  • this.date; 调用本类属性;
  • this.func(); 调用本类方法。

代码示例

super

public class TestSuperAndThis extends Person{
    public int length;
    public String name;

    public TestSuperAndThis(int length, String name) {
        super(name);
        this.length = length;
        this.name = name;
    }

    public void function() {
        super.method();
        System.out.println(super.name);
    }
    
    public static void main(String[] args) {
        TestSuperAndThis test = new TestSuperAndThis(18,"逍遥");
        test.function();
    }
}

class Person {

    /**
     * 3. 调用父类的属性
     */
    public String name;

    /**
     * 1. 调用父类构造方法
     * @param name
     */
    public Person(String name) {
        System.out.println(name + "调用了父类的构造方法");
    }

    /**
     * 2. 调用父类的普通方法
     */
    public void method() {
        System.out.println("调用父类的普通方法");
    }
}
逍遥调用了父类的构造方法
调用父类的普通方法
null

this

public class TestSuperAndThis {
    public int length;
    public String name;

    /**
     * 1. 调用本类的构造方法
     * @param name
     */
    public  TestSuperAndThis(String name) {
        this();
    }

    public TestSuperAndThis() {
        System.out.println("调用本类的其他构造方法");
    }


    /**
     * 2. 调用本类的普通方法
     */
    public void function() {
        this.method();
    }

    /**
     * 3. 调用本类的属性
     */
    public void method() {
        System.out.println("调用本类的普通方法");
        String newName = this.name;
        System.out.println(newName);
    }
    public static void main(String[] args) {
        TestSuperAndThis test = new TestSuperAndThis("逍遥");
        test.function();
    }
}
调用本类的其他构造方法
调用本类的普通方法
null
posted on 2021-07-23 21:16  豆本豆红枣豆奶  阅读(9)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3