How to create objects from a class with private constructor?

前端 未结 6 1533
花落未央
花落未央 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:50
    public class demo
    {
        private demo()
        {
    
        }
        public static demo getObject()
        {
            return new demo();
        }
    
        public void add()
        {
    
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            demo d1 = demo.getObject();
            d1.add();
        }
    }
    
    0 讨论(0)
  • 2021-01-14 00:53
    Class<?> class = Class.forName("SomeClassName"); 
    Constructor<?> constructor = class.getConstructors[0];
    constructor.setAccessible(true);
    

    To convert the privately declared constructor to the public one till program execution. Also, this concept is related to Reflection API.

    Object o = constructor.newInstance();
    if(o.equals(class)) {
        System.out.println("Object for \"SomeClassName\" has been created");
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-14 01:13

    You should define your init method as static, implementing the static factory method that Braj talks about. This way, you create new cards like this:

    Card c1 = Card.init(...);
    Card c2 = Card.init(...);
    ...
    
    0 讨论(0)
  • 2021-01-14 01:13

    Note : You can access private constructor from within the class itself as in a public static factory method.
    You can access it from the enclosing class it its a nested class.

    0 讨论(0)
  • 2021-01-14 01:14

    I would say don't make the constructor private, don't make the build code under the constructor (place it in a new method, which can be private) and make a method to return the card outside the class.

    Then use the card object and call the method to retrieve your card from the Card class, make sure to declare the type Card and make sure that the method returns properly.

    0 讨论(0)
提交回复
热议问题