Reputation: 81
abstract class Coin{
String name;
String currency;
class EUR extends Coin{
EUR() {
super("EUR", "€");
}
}
class USD extends Coin{
USD() {
super("USD", "$");
}
}
private Coin (String name, String currency){
this.name = name
this.currency = currency}
}
class Person{
///variables
Coin coin;
Person(//Variables, Coin coin){
//Other assignments
this.coin = coin
}
}
Basically i would like to initialize a Person passing EUR as Coin, without creating a new EUR. Something like
static final EUR euro = EUR
and then:
Person person = new Person(... , euro);
I do not need millions of instances of EUR so i don't want to create each time a new EUR
I know i can make something like this using constant Strings, but i actually want to pass a Coin object
I also tried initializing EUR inside Coin class like this
static EUR euro = new EUR();
But IDE is warning me this could cause thread deadlock
Upvotes: 2
Views: 60
Reputation: 312106
This is a perfect job for an enum:
public enum Coin {
EUR("EUR", "€"),
USD("USD", "$");
private String name;
private String currency;
private Coin(String name, String currency) {
this.name = name;
this.currency = currency;
}
}
Once you've defined it, you can use the enum constants:
Person person = new Person(... , Coin.EUR);
Upvotes: 5