简体   繁体   English

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

[英]How to create objects from a class with private constructor?

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. 类卡具有私有属性和构造函数,只有函数init是公共的。 Function init checks values for plausibility and if everything is fine than the constructor gets the values and creates an object. 函数init检查值的合理性,如果一切正常,则构造函数获取值并创建一个对象。 Now I wannt in class Game to create an object from class Card. 现在我在课堂游戏中创建一个Card类的对象。 How should I do this? 我该怎么做?

Here is my code: 这是我的代码:

Class Game: 课堂游戏:

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 Card: 类卡:

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

You should define your init method as static, implementing the static factory method that Braj talks about. 您应该将init方法定义为static,实现Braj谈论的静态工厂方法。 This way, you create new cards like this: 这样,您可以像这样创建新卡:

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

As @Braj mentioned in comments, you can use static factory. 正如@Braj在评论中提到的,你可以使用静态工厂。 Private constructor cannot be accessed outside of class, but it can be accessed from inside, like the following: 私有构造函数不能在类外部访问,但可以从内部访问,如下所示:

public class Test
{

    private Test(){

    }

    static Test getInstance(){
        return new Test();
    }
}

This pattern can be used for making Builders, for example. 例如,该模式可用于制作建造者。

Note : You can access private constructor from within the class itself as in a public static factory method . 注意:您可以像在公共静态工厂方法中一样从类本身访问私有构造函数。
You can access it from the enclosing class it its a nested class. 您可以从封闭类访问它,它是一个嵌套类。

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

I would say don't make the constructor private, don't make the build code under the constructor (place it in a new method, which can be private) and make a method to return the card outside the class. 我想说不要将构造函数设为私有,不要在构造函数下创建构建代码(将它放在一个新方法中,这可以是私有的)并创建一个方法将卡返回到类外。

Then use the card object and call the method to retrieve your card from the Card class, make sure to declare the type Card and make sure that the method returns properly. 然后使用卡对象并调用方法从Card类中检索您的卡,确保声明类型卡并确保方法正确返回。

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

To convert the privately declared constructor to the public one till program execution. 将私有声明的构造函数转换为公共构造函数直到程序执行。 Also, this concept is related to Reflection API. 此外,此概念与Reflection API有关。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用包私有构造函数创建类? - How to create a class with a package private constructor? 使用私有构造函数创建类的对象 - Creating objects of a class with private constructor 从文件中读取,然后创建私有 class 的对象 - read from file then create objects of private class 如何从子类构造函数调用超类的私有构造函数? - How to call private constructor of super class from child class constructor? 如何使用来自另一个类的私有变量打印默认构造函数 - how to print the default constructor with private variables from another class 如何使用私有构造函数从final类运行该方法? - How to run the method from final class with private constructor? 使用 java 中另一个 class 的构造函数在不同的类中创建对象 - using constructor from another class in java to create objects in separate classs 如何创建一个构造函数,该构造函数采用包含整数和对象数组的类的能力 - How to create a constructor that takes the capacity of a class that contains an integer and an array of objects 如何在具有私有构造函数的本地内部类的外部创建实例? - How is it possible to create instance outside class of local inner class having private constructor? 如何使用具有私有构造函数的类的实例? - How to use an instance of a class that has a private constructor?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM