如何使用私有构造函数从类创建对象? [英] How to create objects from a class with private constructor?

查看:81
本文介绍了如何使用私有构造函数从类创建对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个班级游戏,这是我的主要班级,还有一个二级班级卡. 类卡具有其属性,构造函数是私有的,只有函数init是公共的. 函数初始化检查值的合理性,如果一切都好,则构造函数将获取值并创建一个对象. 现在我想在Game类中从Card类创建对象. 我该怎么办?

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?

这是我的代码:

职业游戏:

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

类卡:

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

推荐答案

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

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

这篇关于如何使用私有构造函数从类创建对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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