How to create objects from a class with private constructor?

前端 未结 6 1522
花落未央
花落未央 2021-01-14 00:39

I have a class Game that is my main class and a second class Card. Class Card hast its properties and constructor private, only function init is public. Function init checks

6条回答
  •  伪装坚强ぢ
    2021-01-14 00:59

    As @Braj mentioned in comments, you can use static factory. Private constructor cannot be accessed outside of class, but it can be accessed from inside, like the following:

    public class Test
    {
    
        private Test(){
    
        }
    
        static Test getInstance(){
            return new Test();
        }
    }
    

    This pattern can be used for making Builders, for example.

提交回复
热议问题