I'm trying to make an abstract class, and while I'm instantiating a new object of that class, I'm trying to set a variable in the class.
abstract class TestClass { // Class I'm trying to change a variable in.
public String testString;
}
public class Main {
public static void main(String[] args) {
TestClass t = new TestClass() {
public String testString = "TEST"; // Where I'm trying to set it
};
System.out.println(t.testString);
}
}
Output:
null
I wan't it to output out "TEST".
Is there any way to make that happen using a method like the one I'm trying to do?
You should use an initializer block:
TestClass t = new TestClass() {
{ // initializer block
testString = "TEST";
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With