我有一个子类和一个超类。在子类中,当我想检索超类的值时super.i
它super.one
显示为零 - 为什么?
另外,当我扩展超类时,是否需要使用super
关键字调用超类方法?
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;
}
}