Wednesday 19 June 2019

java - 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.
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?



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_set = new Vector();
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;
}
}
}

Answer



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

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...