在枚举单例中调用参数化构造函数? [英] Call parametrised constructor in enum singleton?

查看:284
本文介绍了在枚举单例中调用参数化构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个枚举类:

enum C1 {
    INSTANCE("");

    C1(String s) {
        System.out.println("with param = " +s);
    }
    C1() {
        System.out.println("without param");
    }   
    public void g() {
        System.out.println("inside g");
    }
}

public class Main {
    public static void main(String s[]) {
        C1.INSTANCE.g();
        C1.INSTANCE.g();

    }
}

我怎么称呼 C1(String s)构造函数,使用 INSTANCE 通过传递自定义参数?

How can i call C1(String s) constructor using INSTANCE by passing custom parameter ?

推荐答案

您可以像这样

    enum C1 {
        WITH_PARAM("value"),
        EMPTY();

        private String value;
        C1(String s) {
            System.out.println("with param = " +s);
            value=s;
        }
        C1() {
            System.out.println("without param");
        }
        public void g() {
            System.out.println("inside g, value is "+value);
        }
    }

        public static void main(String s[]) {
            C1.EMPTY.g();
            C1.WITH_PARAM.g();

        }

这篇关于在枚举单例中调用参数化构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆