I have a question, now i have two classes as following
public class mainClass {
public static void main(String[] args){
String st1="st1";
String st2= "st2";
System.out.println(st1);
System.out.println(st2);
testClass t1=new testClass(st1);
testClass t2=new testClass(st2);
System.out.println(t1.getString());
System.out.println(t2.getString());
}
}
public class testClass {
static String testString1;
public testClass(String a ) {
testString1=a;
}
public String getString(){
return testString1;
}
}
output
st1
st2
st2
st2
shouldn’t output be the following?
st1
st2
st1
st2
since I created two instances of testClass, each has different input, why am i getting same output??
Your
testString1variable intestClassis declared static, so it will hold the same value across all instances oftestClass.If you want
testString1to hold a unique value for each instance of testClass that gets created, then you need to remove the static declaration.