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

我有一个类游戏,是我的主要类和第二类卡。 类卡具有私有属性和构造函数,只有函数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_set = new Vector(); 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 = 15 && this.index = 26 && 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方法定义为static,实现Braj谈论的静态工厂方法。 这样,您可以像这样创建新卡:

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

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

 public class Test { private Test(){ } static Test getInstance(){ return new Test(); } } 

例如,该图案可用于制造建造者。

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

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

我想说不要让构造函数私有,不要在构造函数下创建构建代码(将它放在一个新方法中,这可以是私有的)并创建一个方法将卡返回到类外。

然后使用卡对象并调用方法从Card类中检索您的卡,确保声明类型卡并确保方法正确返回。

 Class class = Class.forName("SomeClassName"); Constructor constructor = class.getConstructors[0]; constructor.setAccessible(true); 

将私有声明的构造函数转换为公共构造函数直到程序执行。 此外,此概念与Reflection API有关。

 Object o = constructor.newInstance(); if(o.equals(class)) { System.out.println("Object for \"SomeClassName\" has been created"); }