Java Variable Initialization
- by Samuel Brainard
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.