0

I have interface Cat that is implemented by classes LolCat and FatCat. My program needs to remember which type of Cat user wanted melt with next. I cannot instantiate the proper Cat yet, so I need to remember the class. How do I do this?


I tried:

Class nextCatClass = FatCat.class;

But now I don't know how to instantiate it using a variable. new nextCatClass() is not a valid syntax. I also tried

Class<Cat> nextCatClass = FatCat.class;

but now I get an "incompatible types" error.


Risking to annoy the heck out of Java users, here's what I'd do in Python:

next_cat_class = FatCat
...
instance = next_cat_class()
4
  • This is possible, but messy. Alternatively, can you just store, e.g., the string "FatCat" or "LolCat" in your list, and then do if(catType == "FatCat") { return new FatCat(); } else { return new LolCat(); }? (Of course you may want to use enumerated types, etc., but just something using this principle?) Commented Nov 5, 2019 at 23:33
  • 1
    Regarding Class<Cat> nextCatClass = FatCat.class; read: stackoverflow.com/questions/2745265/… Commented Nov 5, 2019 at 23:34
  • @Tom I am not sure how I should proceed regarding the "possible duplicate". Technically it could answer my question, but I find the accepted answer of this question better (more elegant solution, at least in my case). Advice? Commented Nov 6, 2019 at 0:00
  • 1
    Nothing bad should happen with your question when you accept the duplicate. Then it works like a sign post to the other, duplicated question. But your question can still contain this answer. But you're still free to disagree with the duplicate. But mind that other users with at least 3000 reputation points can still vote to close your question. Commented Nov 6, 2019 at 0:03

1 Answer 1

1

You could use lambda Suppliers:

    public static void main(String args[]) {
        Supplier<Cat> lolCatSupplier = LolCat::new;
        Supplier<Cat> fatCatSupplier = FatCat::new;
        Cat lolCat = lolCatSupplier.get();
        Cat fatCat = fatCatSupplier.get();
        System.out.println(lolCat.getClass());
        System.out.println(fatCat.getClass());
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Works like a charm, but now I need to learn what the heck are these :D
They are basically anonymous, single-method interface implementations - in a short syntax. lambda expressions
Neat solution, but you can also simply encapsulate the creational logic in a factory. This creational pattern returns you, based on your condition (class type, simple string or better yet an enum value), a class instance when you need it without writing the creational logic in the middle of your method. Simpler to understand, if lambdas are not that familiar to you...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.