This site requires JavaScript, please enable it in your browser!
Greenfoot back
Psychpsyo
Psychpsyo wrote ...

2016/8/23

Don't get subclasses

Psychpsyo Psychpsyo

2016/8/23

#
Is there a way to modify the getObjects() method so it doesn't return subclasses of the class it should return?
danpost danpost

2016/8/23

#
Psychpsyo wrote...
Is there a way to modify the getObjects() method so it doesn't return subclasses of the class it should return?
If you have to ask this question, then it is apparent that you do not understand what subclassing is for. Explain what class you would like to use the method on and what class or classes you do not want returned that are subclasses of that class. Also, explain what type object each of those classes is for.
davmac davmac

2016/8/23

#
No. But if you need to do that, it might indicate a problem with your general design - perhaps you have classes extending (subclassing; inheriting from) other classes when they shouldn't. What you can of course do is filter the list returned by getObjects(), after it is returned. That is, for each item in the list, call getClass() and check if the result is equal to the class you're looking for:
     List<Apple> l = getObjects();
     List<Apple> filtered = new ArrayList<Apple>();
     for (Apple a : l) {
         if (a.getClass() == Apple.class) {
             // a is an Apple, but not a subclass of Apple
             filtered.add(a);
         }
     }
Psychpsyo Psychpsyo

2016/8/23

#
Ok. Thanks for the answers.
danpost danpost

2016/8/23

#
@davmac, should not your first line read: List<Apple> l = getObjects(Apple.class); ? @PsychoPsyo, you might consider reviewing the first three lessons of the java tutorials on Object Oriented Programming Concepts. Those would be "What is an Object?", "...Class?" and "...Inheritance?".
davmac davmac

2016/8/23

#
danpost wrote...
@davmac, should not your first line read: List<Apple> l = getObjects(Apple.class); ?
Yes, that's correct, sorry.
You need to login to post a reply.