温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java Super超类与this区别

发布时间:2026-10-06 07:05:41 来源:亿速云 阅读:89 作者:小樊 栏目:编程语言

在 Java 中,super 和 this 都是关键字,常用于类中,但它们的作用和指向对象不同。下面从多个角度对比说明。


一、基本含义

this

  • 表示当前对象(当前类的实例)
  • 用于区分成员变量和局部变量
  • 调用当前类的方法或构造方法

super

  • 表示当前对象的父类(超类)部分
  • 用于访问父类的成员变量、方法、构造方法

二、主要区别对比

对比点 this super
指向对象 当前类对象 父类对象(当前对象的一部分)
访问变量 本类成员变量 父类成员变量
调用方法 本类方法 父类方法
调用构造方法 this() super()
是否可单独使用 可以 不可以单独表示对象

三、使用示例

1. 访问成员变量

class Parent {
    int x = 10;
}

class Child extends Parent {
    int x = 20;

    void show() {
        System.out.println(x);      // 20
        System.out.println(this.x); // 20
        System.out.println(super.x);// 10
    }
}

2. 调用成员方法

class Parent {
    void print() {
        System.out.println("Parent");
    }
}

class Child extends Parent {
    void print() {
        System.out.println("Child");
    }

    void test() {
        print();      // Child
        this.print(); // Child
        super.print();// Parent
    }
}

3. 构造方法中的使用(非常重要)

class Parent {
    Parent() {
        System.out.println("Parent 构造");
    }
}

class Child extends Parent {
    Child() {
        super(); // 调用父类构造,必须第一行
        System.out.println("Child 构造");
    }
}

✅ super() 和 this() 都必须在构造方法第一行
❌ 不能同时出现

Child() {
    super();
    this(); // 错误
}

四、常见误区

  1. super 不是父类对象
    • 它是“当前对象中属于父类的部分”
  2. static 方法中不能用 this / super
    static void method() {
        this.x;  // 错误
        super.x; // 错误
    }
    
  3. super 不限于直接父类
    • 可以访问间接父类的可访问成员

五、一句话总结

this 指向“我自己”,super 指向“我爸(父类)”

如果你愿意,我也可以用 内存模型图 或 面试常问点 来帮你理解。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手