1

サブクラスとスーパークラスがあります。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;
    }
}
4

3 に答える 3

1

初期化していないため、デフォルトでは値がゼロになります。

hello_weight 

は Box_Weight クラスのオブジェクトであり、そのクラスの setValues を呼び出すと、このクラスの1 つが初期化され、スーパー クラスの 1 つがシャドウされます。だからスーパークラスワンはまだゼロ。

また、コンストラクターで初期化されていません

于 2013-10-26T06:44:05.200 に答える
0

super親クラスのメンバーにアクセスするためにキーワードは必要ありません。ただし、必要なのは、適切なスコープ/可視性を持つことです。

親クラスに とはprotected対照的なフィールドがある場合private、サブクラスのメンバーだけがそれらを見ることができます。

于 2013-10-26T06:44:57.537 に答える
0

変数のデフォルトのスコープはpackage privateです。親クラス変数にアクセスする場合は、それらを作成するprotectedか、子と親の両方を同じパッケージに配置します。

あなたの場合、int width, height, depth, i, one;変数はパッケージプライベートです。したがって、サブクラスがスーパークラスと同じパッケージ内にない場合、サブクラスはそれらにアクセスできません。したがって、それらを として宣言しますprotected

于 2013-10-26T06:58:10.717 に答える