Re: static final int, but constructor with (final int) arguments
On Mon, 28 Mar 2011 19:11:54 +0200, Merciadri Luca
<Luca.Merciadri@student.ulg.ac.be> wrote:
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Hi,
I've got a class constructor which takes two final int arguments; they
come from the CLI and this one is parsed only once, at the beginning
of the programming. Once they have been parsed from the CLI, errors
handled, etc., they never change.
During the program's execution, I need to create two objects from this
class. These objects thus inherit some variables that need to be static final
int. However, the final is not accepted because, in the constructor, I
evidently define one of these variable's values.
To take an example, consider the class foo. You know that
==
public class foo {
You should follow the convention and name your classes starting with a
capital letter: Foo
private static final int c;
public Foo(final int a, final int b) {
This will give you a compiler error, your class is called "foo", not
"Foo". Please do us the courtesy of removing all irrelevant errors
from your code. We are going to by copying your code into our IDEs;
you would do well to do the same first, so that it does not distract
with avoidable errors.
c = 2*a;
}
}
==
will produce an error because c cannot be modified. I can understand
it, and I thus tried to put the final keyword in the constructor, just
before `c', but to no avail. I tried various combinations, using
static blocks, etc., but nothing more.
Do you have any reasonable way to achieve this?
You can't, at least not the way you are trying to do it. By declaring
c as static final you are telling the compiler that there is one
single unchanging value of c for all instances of the Foo class. That
means that c cannot vary according to the parameters of the
constructor of an individual instance of the class.
Consider:
Foo foo1 = new Foo(42, 100);
Foo foo2 = new Foo(24, 330);
System.out.println("c = " + Foo.getC());
What value should c have? 84? 48? something else?
You are not thinking clearly about the implications of declaring c as
static.
One solution to your problem may be:
class Foo {
private static final int c = 99;
public Foo(int a, int b) {
// Stuff not assigning a value to c.
}
}
another solution may be:
class Foo {
private final int c;
public Foo(int a, int b) {
c = 2*a;
}
}
or possibly something else. The correct solution depends on how you
want c to behave.
rossum