super关键字

uper在父类、子类相关联的操作中经常被用到

super 是Java中的关键字,用于引用父类(超类)的成员变量、方法或构造函数。它有以下主要用途:

  1. 访问父类中的成员变量
  2. 调用父类中的构造方法
  3. 调用父类中的方法

1、访问父类的成员变量

使用 super 关键字可以在子类中访问父类中的成员变量。这对于在子类中有相同名字的成员变量时很有用,以便明确指定你想要访问的是父类的成员变量。

package com.sky.test;
 
class Parent {
    int x = 10;
}
 
class Child extends Parent {
    int x = 20;
 
    void display() {
        System.out.println(super.x); // 访问父类的x变量    10 
        System.out.println(this.x);    // 访问子类的x变量  20
    }
}
 
public class Main {
    public static void main(String[] args) {
        Child child = new Child();
        child.display();
    }
}
class Animal {
    String name = "Animal"; // 父类的成员变量
 
    void printName() {
        System.out.println(name); // 打印父类的成员变量
    }
}
 
class Dog extends Animal {
    String name = "Dog"; // 子类的成员变量
 
    void displayNames() {
        System.out.println(name);     // 打印子类的成员变量
        System.out.println(super.name); // 打印父类的成员变量
    }
}
 
public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        myDog.printName();    // 输出:Animal(调用父类方法)
        myDog.displayNames(); // 输出:Dog(子类成员变量),Animal(父类成员变量)
    }
}

2、调用父类中的构造方法

经常用在下面这种情况,类中有些变量是子类继承父类的

利用super可调用父类的构造方法将其赋值

class Parent {
    int x;
 
    Parent(int x) {
        this.x = x;
    }
}
 
class Child extends Parent {
    int y;
 
    Child(int x, int y) {
        super(x); // 调用父类构造函数  将x赋值
        this.y = y;
    }
 
    // @Override 不理解也没事,不带上这个注解一样能正常运行
    @Override  // java中的注解 此处的意思是表明此方法是重写过的方法
    public String toString() {   // 返回带上child的成员变量值的字符串 x和y
        return "Child{" +
                "y=" + y +
                ", x=" + x +
                '}';
    }
}
 
public class Main {
    public static void main(String[] args) {
        Child child = new Child(10, 20);
        System.out.println(child.toString());
    }
}

3、调用父类中的方法

使用 super 关键字可以在子类中显式调用父类的方法。这在子类重写父类的方法时特别有用,以便在子类中可以调用父类的版本。

class Parent {
    void print() {
        System.out.println("Parent's print method");
    }
}
 
class Child extends Parent {
    @Override
    void print() {
        super.print(); // 调用父类的print方法
        System.out.println("Child's print method");
    }
}
 
 
public class Main {
    public static void main(String[] args) {
        Child child = new Child();
        child.print();
    }
}
posted @   蜡笔小新Belief  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
· 零经验选手,Compose 一天开发一款小游戏!
点击右上角即可分享
微信分享提示