如何使用私有构造函数从类创建对象?

CMS*_*CMS 2 java oop

我有一个类游戏,是我的主要类和第二类卡.类卡具有私有属性和构造函数,只有函数init是公共的.函数init检查值是否合理,如果一切正常,则构造函数获取值并创建一个对象.现在我在课堂游戏中创建一个Card类的对象.我该怎么做?

这是我的代码:

课堂游戏:

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);
     }
   }
 }
Run Code Online (Sandbox Code Playgroud)

类卡:

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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Jor*_*e_B 9

您应该将init方法定义为static,实现Braj谈论的静态工厂方法.这样,您可以像这样创建新卡:

Card c1 = Card.init(...);
Card c2 = Card.init(...);
...
Run Code Online (Sandbox Code Playgroud)


nik*_*kis 6

正如@Braj在评论中提到的,你可以使用静态工厂.私有构造函数不能在类外部访问,但可以从内部访问,如下所示:

public class Test
{

    private Test(){

    }

    static Test getInstance(){
        return new Test();
    }
}
Run Code Online (Sandbox Code Playgroud)

例如,该模式可用于制作建造者.


小智 5

注意:您可以像在公共静态工厂方法中一样从类本身访问私有构造函数.
您可以从封闭类访问它,它是一个嵌套类.