How to create objects from a class with private constructor?

11,989

Solution 1

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(...);
...

Solution 2

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.

Solution 3

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();
    }
}

Solution 4

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.

Solution 5

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");
}
Share:
11,989
CMS
Author by

CMS

ASP.net Core and C#,Entity Framework, JavaScript, Angular, Apache, HTML5

Updated on June 13, 2022

Comments

  • CMS
    CMS almost 2 years

    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 values for plausibility and if everything is fine than the constructor gets the values and creates an object. Now I wannt in class Game to create an object from class Card. How should I do this?

    Here is my code:

    Class Game:

    import java.util.List;
    import java.util.Vector;
    
    
    public class Game {
    
    
    public  static void main(String[] args)
    {
       /*
    CREATING NEW CARD OBJECT
     */
    
        int value = 13;
        Vector<Card> _card_set = new Vector<Card>();
        for (int i = 2; i < 54; i++)
        {
    
            if(--value == 0)
            {
                value = 13;
            }
    
            Card _myCard;
            _myCard.init(i,value);
         }
       }
     }
    

    Class Card:

    public class Card {
    
    private int index;
    private  int value;
    private String symbol;
    
    /*
    CREATING A PLAYCARD
    */
    
    private Card(int index,int value)
    {
        this.index = index;
        this.value = value;
        value = (int) Math.floor(index % 13);
    
        if(this.index >= 2 && this.index <= 14)
        {
            this.symbol = "KARO";
        }
        else if (this.index >= 15 && this.index <= 27)
        {
            this.symbol = "HERZ";
        }
        else if (this.index >= 26 && this.index <= 40)
        {
            this.symbol = "PIK";
        }
        else if (this.index >= 41 && this.index <= 53)
        {
    
            this.symbol = "KREUZ";
        }
        System.out.println("Card object wurde erstellt: " + symbol + value);
        System.out.println("------<><><><>------");
    }
    
    /*
    SHOW FUNCTION
    GET DETAILS ABOUT PLAYCARD
     */
    public String toString()
    {
        return "[Card: index=" + index + ", symbol=" + symbol + ", value=" + value + "]";
    }
    
    /*
    Initialize Card object
     */
    
    public Card init(int index, int value)
    {
        /*
        Check for plausibility
        if correct constructor is called
         */
    
        if((index > 1 || index > 54) && (value > 0 || value < 14))
        {
           Card myCard = new Card(index,value);
            return  myCard;
        }
        else
        {
            return null;
        }
      }
    }