Reputation: 2558
I'm fairly new to Java and I am coming to it from a C++ background. I am working with a class that has to be extended before it's protected constructor is called. I only need the class in one instance. Is there a way I can dynamically create the class AND instantiate it at the same time?
I found similar posts but not quite hitting the mark. I have the following code as an example but of course it's syntactically incorrect.
final ffd.tokens.CountryTokens cToken = new class USA extends ffd.tokens.CountryTokens
{
USA (String value)
{
super(value);
}
} ("USA");
Upvotes: 0
Views: 204
Reputation: 1102
Something like this?
final ffd.tokens.CountryTokens cToken = new ffd.tokens.CountryTokens("someValue")
{
// override something
};
Corrections:
Even with protected methods you can create a Builder that will extend ffd.tokens.CountryTokens
(pretty crazy huh?)
public abstract class CountryBuilder extends ffd.tokens.CountryTokens {
public CountryBuilder () { super("useless-data"); }
public abstract ffd.tokens.CountryTokens build (String val);
}
Using:
CountryBuilder builder = new CountryBuilder (){
@Override
public ffd.tokens.CountryTokens build(String val) {
return new ffd.tokens.CountryTokens(val) {};
}
};
builder.build("USA");
builder.build("Canada");
I think you get the idea.
Upvotes: 1
Reputation: 2558
I think I got it. I'm always thinking dynamic allocation with Java but if I simply create a local instance I did it this way.
class USA extends ffd.tokens.CountryTokens
{
public USA() { super("USA"); }
} USA country;
Now I have my local variable country
of type USA
.
Upvotes: 0