我有一个类游戏,它是我的主类,还有一个二类卡牌。
Card 类的属性和构造函数是私有的,只有函数 init 是公共的。
函数 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);
}
}
}
班级卡:
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
method 为 static,实现了 Braj 所说的静态工厂方法。这样,您就可以创建如下新卡:
Card c1 = Card.init(...);
Card c2 = Card.init(...);
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)