Java关键字 您所在的位置:网站首页 瑞丽小额贷款公司需要什么条件 Java关键字

Java关键字

2024-01-01 05:55| 来源: 网络整理| 查看: 265

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

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

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

在没有继承和被继承关系的类中,几乎不被使用

我个人喜欢将super理解为 “父类的”, “引用父类的”

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 关键字可以调用父类的构造函数。这通常用于初始化父类的成员变量或执行父类构造函数的逻辑。

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

利用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(); } }



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有