Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Changing variables while instantiating an abstract class

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?

like image 372
AbundanceOfNames Avatar asked May 20 '26 00:05

AbundanceOfNames


1 Answers

You should use an initializer block:

TestClass t = new TestClass() {
    { // initializer block
        testString = "TEST";
    }
};
like image 128
fps Avatar answered May 23 '26 22:05

fps