0

grid[targetheight][targetwidth].setValue(variable)

So, there is a specific element of this matrix at targetheight and targetwidth. I want to modify this element using a method only available to WhiteBox, setValue. But since setValue isn't a method declared by the interface Box, I am SOL. How can I access it? Grid is supposed to store a bunch of boxes, but some of those boxes are different and I want to do different things to them. I am so confused please help.

EDIT: Why does

((WhiteBox) grid[targetheight][targetwidth]).setValue(v);

work but

(WhiteBox) grid[targetheight][targetwidth].setValue(v);

doesn't?

Daniel Paczuski Bak
  • 3,720
  • 8
  • 32
  • 78
  • 2
    You're not turning the `Box` into a `WhiteBox`, you're stating, beyond what the compiler can determine (hence the explicit cast), that that `Box` is in fact a `WhiteBox` (and if it isn't, you'll get a `ClassCastException` at runtime). As for the second question, put the call inside a type check: `if(grid[targetheight][targetwidth] instanceof WhiteBox) { ((WhiteBox) grid[targetheight][targetwidth]).setValue(variable); }` – watery Jan 21 '15 at 20:46
  • @Watery: Why does (WhiteBox) grid[targetheight][targetwidth].setValue(v); make a ton of errors but ((WhiteBox) grid[targetheight][targetwidth]).setValue(v); (or, for that matter, your version) work? I already checked that that element was an instance of WhiteBox, just wondering at why the formatting on my end doesn't work. – Daniel Paczuski Bak Jan 21 '15 at 20:51
  • Because the `.` will take precedente over the cast if you do not use the parentheses. That's a matter of operators precedente. – watery Jan 21 '15 at 20:53

0 Answers0