2

Below is the code snippet and its output -

class Box{
        int height = 1;
        int length = 1;
        int width = 1;

        Box(int h, int l, int w){
                this.height = h;
                this.length = l;
                this.width = w;
        }

        int volume(){
                return this.height * this.length * this.width;
        }

}

class BoxWeight extends Box{
        int height = 99;
        int length = 99;
        int width = 99;
        int mass;

        BoxWeight(int h, int l, int w, int m) {
                super(h, l, w);
                this.mass = m;
        }

        int volume(){
                return this.height * this.length * this.width;
        }
}
public class BoxDemo {
        public static void main(String[] args) {
                Box b = new Box(10, 20, 30);
                BoxWeight bw = new BoxWeight(40, 50, 60, 10);
                System.out.println(bw.height);
                System.out.println(bw.length);
                System.out.println(bw.width);
                //b = bw;
                //System.out.println(b.volume());

        }

}

Output

99
99
99

Here i am not able to get why object bw is printing values initialized as class members. Why object bw is not holding values assigned through constructor?

Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
anil funde
  • 93
  • 1
  • 8
  • actually ultimate aim is not to print 40, 50, 60 , i just wanted to know whats happening behind the scene here. If anyone can put here some good read regarding this, it can be helpful. Which java mechanism working here? – anil funde Apr 14 '15 at 14:43
  • when in BoxWeight constructor ""BoxWeight(40, 50, 60, 10)** is called which again calls **super** to initialize height, width, length i thought all initialization using super will be done on **this** means BoxWeight object which in turn will have values 40, 50, 60. – anil funde Apr 14 '15 at 14:59

3 Answers3

4

The members of BoxWeight hide the members of Box, so you don't see the values you passed to the Box constructor.

Just remove this members from BoxWeight :

        int height = 99;
        int length = 99;
        int width = 99;

It also makes no sense to have the exact same implementation of volume() in both classes.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

Because BoxWeight defines it's own length, width, and height, the corresponding fields in Box are hidden. You can either remove the fields from BoxWeight, or cast to a Box as follows:

public static void main(String[] args) {
    Box b = new Box(10, 20, 30);
    BoxWeight bw = new BoxWeight(40, 50, 60, 10);
    System.out.println(((Box) bw).height);
    System.out.println(((Box) bw).length);
    System.out.println(((Box) bw).width);
}

Prints:

40
50
60
Sizik
  • 1,066
  • 5
  • 11
0

That's how Inheritance is working. The last @Override counts. In this case it is the BoxWeight.

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107