面向对象10:Super详解

面向对象10:Super详解

在Java中,super是一个关键字,主要用于在子类中引用其父类的成员(属性、方法或构造方法)。它在继承关系中扮演重要角色,帮助子类访问和调用父类的特性。

基本用法

1.调用父类的构造方法

  • 语法:super([参数列表])
  • 注意:必须放在子类构造方法的第一行

示例:

public class Person{

    public Person(){
        System.out.println("Person无参执行了")
    }
}
public class Student extends Person{
    public Student(){
        //隐藏代码;调用了父类的无参构造(不加super())

        super();//调用父类的构造器,必须要在子类的第一行
        System.out.println("Student无参执行了")
    }
}
import com.oop.demo05.Student;

public class Application{
    public static void main(String[] args){
        Student student = new Student();
    }
}

运行结果为:

img

2.调用父类的属性

  • 语法:super.属性名
  • 场景:当子类与父类存在同名属性时,用于明确引用父类的属性。

示例:

public class Person {

    protected String name = "xiaochaole";

}
public class Student extends Person{

    private String name = "小潮乐";

    public void test(String name){
        System.out.println(name);
        System.out.println(this.name);
        System.out.println(super.name);
    }
}
```java
import com.oop.demo05.Student;

public class Application {
    public static void main(String[] args) {
        Student student = new Student();
        
        student.test("qinjiang");
    }
}

运行结果为:

img

3.调用父类的方法

  • 语法:super.方法名([参数列表])
  • 场景:当子类重写父类的方法后,需要调用父类的原始实现。

示例:

public class Person {

    public void print(){
        System.out.println("Person");
    }
}
public class Student extends Person{

    public void print(){
        System.out.println("Student");
    }

    public void test1(){
        print();
        this.print();
        super.print();
    }
}
import com.oop.demo05.Student;

public class Application {
    public static void main(String[] args) {
        Student student = new Student();

        student.test1();
    }
}

运行结果为:

img

使用规则

1. 构造方法调用规则

  • 子类构造方法默认会隐式调用父类的无参构造方法(super())。
  • 如果父类没有无参构造方法,子类必须显示使用super(...)调用父类的有参构造方法。
  • super和this不能同时调用构造方法。

2.访问权限

  • super只能访问父类中声明为publicprotected或默认访问权限的成员。
  • 无法访问父类的private成员。

3.静态方法中的限制

  • super不能在静态方法(static)中使用,因为静态方法属于类,不关联具体对象。
  • super必须只能出现在子类的方法或者构造方法中。

super与this关键字的区别

特性 this super
指向对象 当前对象实例 父类的成员(属性/方法/构造方法)
前提 没有继承也可以使用 只能在继承条件下才可以使用
构造方法调用 调用本类其他构造方法 调用父类构造方法
解决命名冲突 区分局部变量与成员变量 访问父类被隐藏的属性或方法
静态上下文中使用 ×不可用 ×不可用
posted @ 2025-07-23 12:19  消消小潮乐  阅读(45)  评论(0)    收藏  举报