gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:56:24 26 4
gpt4 key购买 nike

我有一个子类和一个父类(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com