Re: Can you declare classes' variable in constructor?
BillJosephson wrote:
Ingo R. Homann wrote:
Hi,
just like Andrew, I am not sure if I understand your problem correctly.
Is it just that you stumble about the following?:
String[] s={"a","b","c"};
vs
String[] s=new String[]{"a","b","c"};
Ciao,
Ingo
Many thanks, everyone. It seems to be the case that one can not declare
an instance varible in a constructor. I thought this might save memory
etc by having different constructors for different situations, and if
the instance variables were created in constructor, only the relevant
instance variables would get created depending on which constructor you
used. But I see this is not the case. Guess it doesn't make sense
anyway, when you think about what it means to "define a class". My
hoped for approach would be more a case of improvising a class on the
fly.
Thanks again.
Is this what you are trying to do?
public class test {
String[] str;
int[] ints;
public test(String[] strArray) {
str = strArray;
}
public test(int[] intArray) {
ints = intArray;
}
public void output() {
if (str != null)
for (int i=0; i<str.length; i++)
System.out.println(str[i]);
if (ints != null)
for (int i=0; i<ints.length; i++)
System.out.println(ints[i]);
}
public static void main(String[] args) {
// test t = new test(new int[] {1,2,3,4,5});
test t = new test(new String[] {"1","2","3","4","5"});
t.output();
}
}
--
Knute Johnson
email s/nospam/knute/