Java Variable Initialization

Posted by Samuel Brainard on Stack Overflow See other posts from Stack Overflow or by Samuel Brainard
Published on 2012-10-16T22:56:24Z Indexed on 2012/10/16 23:00 UTC
Read the original article Hit count: 154

Filed under:

Here's a piece of code I wrote.

public class cube { 
private int length;
private int breadth;
private int height;
private int volume;
private int density;
private int weight;
public cube(int l,int b,int h, int d)  {
    length=l;
    breadth=b;
    height=h;
    density=d;
}

public void volmeShow(){
volume=length*breadth*height;
System.out.println("The Volume of the cube is "+this.volume);

So if I implement the above cube class like this,

public class cubeApp {
     public static void main(String[] args){
    cube mycube = new cube(5,6,9,2);
    mycube.volumeShow();

I get an output that tells me Volume is 270.

But I get an output that says Volume is 0 if I define the volume variable like this:

public class cube { 
private int length;
private int breadth;
private int height;
private int volume=length*breadth*height;
private int density;
private int weight;
public cube(int l,int b,int h, int d)  {
    length=l;
    breadth=b;
    height=h;
    density=d;
}

public void volmeShow(){
System.out.println("The Volume of the cube is "+this.volume);

Can somebody please explain why this is happening?

Thanks, Samuel.

© Stack Overflow or respective owner

Related posts about java