gpt4 book ai didi

java - 如何使用私有(private)构造函数从类创建对象?

转载 作者:行者123 更新时间:2023-12-01 06:42:48 25 4
gpt4 key购买 nike

我有一个类游戏是我的主要类和第二类卡。
类 Card 的属性和构造函数是私有(private)的,只有函数 init 是公共(public)的。
函数 init 检查值的合理性,如果一切正常,则构造函数获取值并创建一个对象。
现在我想在 Game 类中从 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);
}
}
}

类(class)卡:
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 所说的静态工厂方法。这样,您可以像这样创建新卡片:

Card c1 = Card.init(...);
Card c2 = Card.init(...);
...

关于java - 如何使用私有(private)构造函数从类创建对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23871173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com