-3
public class Box{

    public int length,width,height;
    public int volume;
    Box(int i, int j, int k){
        this.length=i;
        this.width=j;
        this.height=k;
    }
    void setvolume(int i){
        this.volume=i;
    }
    int getvolume(){
        return volume;
    }
}
class BigBox{

    Box B1=new Box(20,30,40);
    B1.length=30;

}

I created a class Box and another class BigBox which overwrites the length variable of the object of the class Box to 30. But when I write the code B1.length=30 to overwrite it, it shows an error I am unable to understand. Can anyone help me out?

markspace
  • 10,621
  • 3
  • 25
  • 39
Prabhjot Rai
  • 27
  • 1
  • 3

2 Answers2

3

You need to put assignments like that inside a code block, usually a method or maybe an initializer block.

class BigBox{
   public void someMethod() {
    Box B1=new Box(20,30,40);
    B1.length=30;
   }
}

If you really are trying to initialize an instance variable, this will work:

class BigBox{
    Box B1=new Box(20,30,40); 
    {
       B1.length=30;
    }
}
markspace
  • 10,621
  • 3
  • 25
  • 39
  • Thank you! But I didn't understand WHY would we need a method or an initializer block to overwrite the value? Is it because the method or block helps java to understand B1.length is an instance variable of B1 and not an undeclared instance variable of BigBox? – Prabhjot Rai Nov 02 '14 at 05:09
  • Well, by the arbitrary rules of the language, it just says "you can't put that there." You can't put statements in a class outside of a block, just statements that declare and initialize variables. Since B1 is already initialized, you can't access it again unless it's inside a code block. – markspace Nov 02 '14 at 05:57
0

you must declare your object in the method or initialize in the block...