How to call methods within Java Singleton enum constructor?










5















My sample enum Singleton class is:



public class Test

public enum MyClass

INSTANCE;

private static String name = "Hello";

MyClass()
test();


private static void test()
name = name + "World";
System.out.println(name);



public static void main(String a)

MyClass m1 = MyClass.INSTANCE;





Obtained output : nullWorld

Expected output : HelloWorld



In main(), if



MyClass m1 = MyClass.INSTANCE;


is replaced by



MyClass.INSTANCE.test();


then, the output is HelloWorld, as expected.



This shows that static fields are not initialized until the constructor has completed execution.



Question : How to achieve this functionality of calling a method within constructor that accesses static fields?










share|improve this question






















  • Check this: stackoverflow.com/questions/443980/…

    – ernest_k
    Nov 15 '18 at 5:03






  • 2





    @AadhiraiR the whole point of singleton ist to have a single instance that can hold state - why do you need a static variable in a singleton? Just make it an instance variable instead.

    – Hulk
    Nov 15 '18 at 7:24











  • @Hulk, true! I realized that and am removing all the static fields in the enum singleton class.

    – Aadhirai R
    Nov 15 '18 at 9:18















5















My sample enum Singleton class is:



public class Test

public enum MyClass

INSTANCE;

private static String name = "Hello";

MyClass()
test();


private static void test()
name = name + "World";
System.out.println(name);



public static void main(String a)

MyClass m1 = MyClass.INSTANCE;





Obtained output : nullWorld

Expected output : HelloWorld



In main(), if



MyClass m1 = MyClass.INSTANCE;


is replaced by



MyClass.INSTANCE.test();


then, the output is HelloWorld, as expected.



This shows that static fields are not initialized until the constructor has completed execution.



Question : How to achieve this functionality of calling a method within constructor that accesses static fields?










share|improve this question






















  • Check this: stackoverflow.com/questions/443980/…

    – ernest_k
    Nov 15 '18 at 5:03






  • 2





    @AadhiraiR the whole point of singleton ist to have a single instance that can hold state - why do you need a static variable in a singleton? Just make it an instance variable instead.

    – Hulk
    Nov 15 '18 at 7:24











  • @Hulk, true! I realized that and am removing all the static fields in the enum singleton class.

    – Aadhirai R
    Nov 15 '18 at 9:18













5












5








5


3






My sample enum Singleton class is:



public class Test

public enum MyClass

INSTANCE;

private static String name = "Hello";

MyClass()
test();


private static void test()
name = name + "World";
System.out.println(name);



public static void main(String a)

MyClass m1 = MyClass.INSTANCE;





Obtained output : nullWorld

Expected output : HelloWorld



In main(), if



MyClass m1 = MyClass.INSTANCE;


is replaced by



MyClass.INSTANCE.test();


then, the output is HelloWorld, as expected.



This shows that static fields are not initialized until the constructor has completed execution.



Question : How to achieve this functionality of calling a method within constructor that accesses static fields?










share|improve this question














My sample enum Singleton class is:



public class Test

public enum MyClass

INSTANCE;

private static String name = "Hello";

MyClass()
test();


private static void test()
name = name + "World";
System.out.println(name);



public static void main(String a)

MyClass m1 = MyClass.INSTANCE;





Obtained output : nullWorld

Expected output : HelloWorld



In main(), if



MyClass m1 = MyClass.INSTANCE;


is replaced by



MyClass.INSTANCE.test();


then, the output is HelloWorld, as expected.



This shows that static fields are not initialized until the constructor has completed execution.



Question : How to achieve this functionality of calling a method within constructor that accesses static fields?







java enums constructor singleton






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 15 '18 at 4:05









Aadhirai RAadhirai R

818




818












  • Check this: stackoverflow.com/questions/443980/…

    – ernest_k
    Nov 15 '18 at 5:03






  • 2





    @AadhiraiR the whole point of singleton ist to have a single instance that can hold state - why do you need a static variable in a singleton? Just make it an instance variable instead.

    – Hulk
    Nov 15 '18 at 7:24











  • @Hulk, true! I realized that and am removing all the static fields in the enum singleton class.

    – Aadhirai R
    Nov 15 '18 at 9:18

















  • Check this: stackoverflow.com/questions/443980/…

    – ernest_k
    Nov 15 '18 at 5:03






  • 2





    @AadhiraiR the whole point of singleton ist to have a single instance that can hold state - why do you need a static variable in a singleton? Just make it an instance variable instead.

    – Hulk
    Nov 15 '18 at 7:24











  • @Hulk, true! I realized that and am removing all the static fields in the enum singleton class.

    – Aadhirai R
    Nov 15 '18 at 9:18
















Check this: stackoverflow.com/questions/443980/…

– ernest_k
Nov 15 '18 at 5:03





Check this: stackoverflow.com/questions/443980/…

– ernest_k
Nov 15 '18 at 5:03




2




2





@AadhiraiR the whole point of singleton ist to have a single instance that can hold state - why do you need a static variable in a singleton? Just make it an instance variable instead.

– Hulk
Nov 15 '18 at 7:24





@AadhiraiR the whole point of singleton ist to have a single instance that can hold state - why do you need a static variable in a singleton? Just make it an instance variable instead.

– Hulk
Nov 15 '18 at 7:24













@Hulk, true! I realized that and am removing all the static fields in the enum singleton class.

– Aadhirai R
Nov 15 '18 at 9:18





@Hulk, true! I realized that and am removing all the static fields in the enum singleton class.

– Aadhirai R
Nov 15 '18 at 9:18












1 Answer
1






active

oldest

votes


















2














This is because INSTANCE is declared before name, so it is created and initalized before name is initialized.



This works:



public enum MyClass{
INSTANCE;
private static final String name = "Hello";

MyClass()
test();


private static void test()
String name1 = name + "World";
System.out.println(name1);






share|improve this answer


















  • 1





    Why does it work by making name final? Are final static variables initialized before static variables even if they are declared after?

    – Kartik
    Nov 15 '18 at 4:36











  • My requirement is to have a static variable that is not final. I want to be able to modify it.

    – Aadhirai R
    Nov 15 '18 at 4:50











  • I know Josh Bloch has suggested this way to implement Singleton pattern in his Effective Java book. But when this approach doesn't work then one should fall back to old approach of making a singleton via class implementation where you can define the name variable before the INSTANCE variable and then not keep it final but still you get your expected output! Is there any force that you have to implement singleton via enum only?

    – Ketan
    Nov 15 '18 at 5:33






  • 1





    @Aadhirai R if it were not enum you could move name before INSTANCE then it would work.

    – Evgeniy Dorofeev
    Nov 15 '18 at 5:37






  • 3





    @Kartik Making it final changes things because the variable is now a compile-time constant. This means the compiler replaces the use of name within test() with the constant value of name. Since this happens at compile-time there is no issue with the order of initialization.

    – Slaw
    Nov 15 '18 at 9:06











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53312274%2fhow-to-call-methods-within-java-singleton-enum-constructor%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














This is because INSTANCE is declared before name, so it is created and initalized before name is initialized.



This works:



public enum MyClass{
INSTANCE;
private static final String name = "Hello";

MyClass()
test();


private static void test()
String name1 = name + "World";
System.out.println(name1);






share|improve this answer


















  • 1





    Why does it work by making name final? Are final static variables initialized before static variables even if they are declared after?

    – Kartik
    Nov 15 '18 at 4:36











  • My requirement is to have a static variable that is not final. I want to be able to modify it.

    – Aadhirai R
    Nov 15 '18 at 4:50











  • I know Josh Bloch has suggested this way to implement Singleton pattern in his Effective Java book. But when this approach doesn't work then one should fall back to old approach of making a singleton via class implementation where you can define the name variable before the INSTANCE variable and then not keep it final but still you get your expected output! Is there any force that you have to implement singleton via enum only?

    – Ketan
    Nov 15 '18 at 5:33






  • 1





    @Aadhirai R if it were not enum you could move name before INSTANCE then it would work.

    – Evgeniy Dorofeev
    Nov 15 '18 at 5:37






  • 3





    @Kartik Making it final changes things because the variable is now a compile-time constant. This means the compiler replaces the use of name within test() with the constant value of name. Since this happens at compile-time there is no issue with the order of initialization.

    – Slaw
    Nov 15 '18 at 9:06
















2














This is because INSTANCE is declared before name, so it is created and initalized before name is initialized.



This works:



public enum MyClass{
INSTANCE;
private static final String name = "Hello";

MyClass()
test();


private static void test()
String name1 = name + "World";
System.out.println(name1);






share|improve this answer


















  • 1





    Why does it work by making name final? Are final static variables initialized before static variables even if they are declared after?

    – Kartik
    Nov 15 '18 at 4:36











  • My requirement is to have a static variable that is not final. I want to be able to modify it.

    – Aadhirai R
    Nov 15 '18 at 4:50











  • I know Josh Bloch has suggested this way to implement Singleton pattern in his Effective Java book. But when this approach doesn't work then one should fall back to old approach of making a singleton via class implementation where you can define the name variable before the INSTANCE variable and then not keep it final but still you get your expected output! Is there any force that you have to implement singleton via enum only?

    – Ketan
    Nov 15 '18 at 5:33






  • 1





    @Aadhirai R if it were not enum you could move name before INSTANCE then it would work.

    – Evgeniy Dorofeev
    Nov 15 '18 at 5:37






  • 3





    @Kartik Making it final changes things because the variable is now a compile-time constant. This means the compiler replaces the use of name within test() with the constant value of name. Since this happens at compile-time there is no issue with the order of initialization.

    – Slaw
    Nov 15 '18 at 9:06














2












2








2







This is because INSTANCE is declared before name, so it is created and initalized before name is initialized.



This works:



public enum MyClass{
INSTANCE;
private static final String name = "Hello";

MyClass()
test();


private static void test()
String name1 = name + "World";
System.out.println(name1);






share|improve this answer













This is because INSTANCE is declared before name, so it is created and initalized before name is initialized.



This works:



public enum MyClass{
INSTANCE;
private static final String name = "Hello";

MyClass()
test();


private static void test()
String name1 = name + "World";
System.out.println(name1);







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 15 '18 at 4:29









Evgeniy DorofeevEvgeniy Dorofeev

106k23143223




106k23143223







  • 1





    Why does it work by making name final? Are final static variables initialized before static variables even if they are declared after?

    – Kartik
    Nov 15 '18 at 4:36











  • My requirement is to have a static variable that is not final. I want to be able to modify it.

    – Aadhirai R
    Nov 15 '18 at 4:50











  • I know Josh Bloch has suggested this way to implement Singleton pattern in his Effective Java book. But when this approach doesn't work then one should fall back to old approach of making a singleton via class implementation where you can define the name variable before the INSTANCE variable and then not keep it final but still you get your expected output! Is there any force that you have to implement singleton via enum only?

    – Ketan
    Nov 15 '18 at 5:33






  • 1





    @Aadhirai R if it were not enum you could move name before INSTANCE then it would work.

    – Evgeniy Dorofeev
    Nov 15 '18 at 5:37






  • 3





    @Kartik Making it final changes things because the variable is now a compile-time constant. This means the compiler replaces the use of name within test() with the constant value of name. Since this happens at compile-time there is no issue with the order of initialization.

    – Slaw
    Nov 15 '18 at 9:06













  • 1





    Why does it work by making name final? Are final static variables initialized before static variables even if they are declared after?

    – Kartik
    Nov 15 '18 at 4:36











  • My requirement is to have a static variable that is not final. I want to be able to modify it.

    – Aadhirai R
    Nov 15 '18 at 4:50











  • I know Josh Bloch has suggested this way to implement Singleton pattern in his Effective Java book. But when this approach doesn't work then one should fall back to old approach of making a singleton via class implementation where you can define the name variable before the INSTANCE variable and then not keep it final but still you get your expected output! Is there any force that you have to implement singleton via enum only?

    – Ketan
    Nov 15 '18 at 5:33






  • 1





    @Aadhirai R if it were not enum you could move name before INSTANCE then it would work.

    – Evgeniy Dorofeev
    Nov 15 '18 at 5:37






  • 3





    @Kartik Making it final changes things because the variable is now a compile-time constant. This means the compiler replaces the use of name within test() with the constant value of name. Since this happens at compile-time there is no issue with the order of initialization.

    – Slaw
    Nov 15 '18 at 9:06








1




1





Why does it work by making name final? Are final static variables initialized before static variables even if they are declared after?

– Kartik
Nov 15 '18 at 4:36





Why does it work by making name final? Are final static variables initialized before static variables even if they are declared after?

– Kartik
Nov 15 '18 at 4:36













My requirement is to have a static variable that is not final. I want to be able to modify it.

– Aadhirai R
Nov 15 '18 at 4:50





My requirement is to have a static variable that is not final. I want to be able to modify it.

– Aadhirai R
Nov 15 '18 at 4:50













I know Josh Bloch has suggested this way to implement Singleton pattern in his Effective Java book. But when this approach doesn't work then one should fall back to old approach of making a singleton via class implementation where you can define the name variable before the INSTANCE variable and then not keep it final but still you get your expected output! Is there any force that you have to implement singleton via enum only?

– Ketan
Nov 15 '18 at 5:33





I know Josh Bloch has suggested this way to implement Singleton pattern in his Effective Java book. But when this approach doesn't work then one should fall back to old approach of making a singleton via class implementation where you can define the name variable before the INSTANCE variable and then not keep it final but still you get your expected output! Is there any force that you have to implement singleton via enum only?

– Ketan
Nov 15 '18 at 5:33




1




1





@Aadhirai R if it were not enum you could move name before INSTANCE then it would work.

– Evgeniy Dorofeev
Nov 15 '18 at 5:37





@Aadhirai R if it were not enum you could move name before INSTANCE then it would work.

– Evgeniy Dorofeev
Nov 15 '18 at 5:37




3




3





@Kartik Making it final changes things because the variable is now a compile-time constant. This means the compiler replaces the use of name within test() with the constant value of name. Since this happens at compile-time there is no issue with the order of initialization.

– Slaw
Nov 15 '18 at 9:06






@Kartik Making it final changes things because the variable is now a compile-time constant. This means the compiler replaces the use of name within test() with the constant value of name. Since this happens at compile-time there is no issue with the order of initialization.

– Slaw
Nov 15 '18 at 9:06




















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53312274%2fhow-to-call-methods-within-java-singleton-enum-constructor%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

How to read a connectionString WITH PROVIDER in .NET Core?

In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

Museum of Modern and Contemporary Art of Trento and Rovereto