java - 使用 super 关键字从子类访问父类(super class)成员

标签 java inheritance super

我有一个子类和一个父类(super class)。在子类中,当我想使用 super.isuper.one 检索父类(super class)的值时,它显示零 - 为什么?

另外,当我扩展父类(super class)时,是否需要使用 super 关键字调用父类(super class)方法?

public class Inherit {
    public static void main(String args[]) {
        System.out.println("Hello Inheritance!");
        Date now = new Date();
        System.out.println(now);
        Box hello = new Box(2, 3, 4);
        BoxWeight hello_weight = new BoxWeight(2, 5, 4, 5);
        hello.volume();
        hello_weight.volume();
        Box hello_old = hello;
        hello = hello_weight;
        //hello.showValues();
        hello.show();
        hello_old.show();
        hello = hello_old;
        hello.show();
        hello.setValues(7, 8);
        hello_weight.setValues(70, 80);
        hello.showValues();
        hello_weight.showValues();
    }
}

class Box {
    int width, height, depth, i, one;
    static int as = 0;

    Box(int w, int h, int d) {
        ++as;
        width = w;
        height = h;
        depth = d;
    }

    void setValues(int a, int k) {
        i = k;
        one = a;
        System.out.println("The values inside super are : " + i + " " + one + " " + as);
    }

    void showValues() {
        System.out.println("The values of BoxWeight : " + i + " " + one);
        //System.out.println("The superclass values : "+ super.i + " " + super.one);
    }

    void volume() {
        System.out.println("Volume : " + width * height * depth);
    }

    void show() {
        System.out.println("The height : " + height);
    }
}

class BoxWeight extends Box {
    int weight, i, one;

    void volume() {
        System.out.println("Volume and weight : " + width * height * depth + " " + weight);
    }

    void setValues(int a, int k) {
        i = k;
        one = a;
    }

    void showValues() {
        System.out.println("The values of BoxWeight : " + i + " " + one);
        System.out.println("The superclass values : " + super.i + " " + super.one);
    }

    BoxWeight(int w, int h, int d, int we) {
        super(w, h, d);
        weight = we;
    }
}

最佳答案

因为您还没有初始化,所以默认情况下它的值为零。

hello_weight 

是Box_Weight类的对象,当您调用该类的setValues时,该类的one被初始化,并且父类(super class)1被遮蔽。所以父类(super class) one 仍然为零。

并且 one 未在构造函数中初始化。

关于java - 使用 super 关键字从子类访问父类(super class)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19603782/

相关文章:

java - 不使用 Firebase 云消息传递或任何其他类似服务的 Android 推送通知

java - 关于java中的继承

java - 泛型与 super

java - 从派生类的实例访问基类方法

java 。扩展 Object 的类中的 super 调用

java - 我需要为聊天客户端分配多少个线程?

java - 这个 el 表达式有什么问题?

java - 由于 jdwp 错误,无法从 IntelliJ IDEA 运行项目

c# - 移除对继承的抽象类引用的依赖

java - 为什么我可以在没有 "throws"关键字的情况下声明一个函数?