What I'm trying to do is
1. Configure an array of Constructor2 as a field for ConstructorTest2_2.
2. Within the main function of Constructor2_3, generate ConstructorTest2_2 and set the value in the field ConstructorTest2_2.
3. Check the contents in println
My schedule is
Yuki
Yuki Corporation
____________
Yuki Corporation
Hosono Corporation
It should be
Yuki
Hosono Corporation
__________
Hosono Corporation
Hosono Corporation
What you intend to write to constructor[1] in ConstructorTest2_2 is
It has been overwritten to constructor[0].
If anyone knows why, I would appreciate it if you could let me know.
Here's the code.
public class ConstructorTest2{
static inta;
static String b;
static boolean c;
public ConstructorTest2(inta, String b, boolean c) {
This.a = a;
This.b = b;
This.c = c;
}
}
public class ConstructorTest2_2 {
ConstructorTest2[] constructor=new ConstructorTest2[2];
public ConstructorTest2_2(){
constructor[0].a=1;
constructor[0].b = "Yuki";
constructor[0].c=true;
System.out.println(constructor[0].b);
constructor[1].a=2;
constructor[1].b = "Hosono";
constructor[1].c=false;
System.out.println(constructor[0].b);
System.out.println("_____________");
}
}
public class ConstructorTest2_3 {
public static void main(String[]args) {
ConstructorTest2_2con=new ConstructorTest2_2();
System.out.println(con.constructor[0].b);
System.out.println(con.constructor[1].b);
System.out.println(con.constructor[0].a);
System.out.println(con.constructor[1].a);
}
}
The static
variable statically maintains a single value in the class and all its derived class instances (new
entities).
Therefore, when constructor[1].b="Hosono";
is written, constructor[0].b
is also rewritten to "Hosono."
Just new ConstructorTest2().b="Hoge";
regardless of the array will rewrite the value of all b in the array.
Remove static
if you want to dynamically retain individual values for each instance.
© 2024 OneMinuteCode. All rights reserved.