Part I
is it possible [...]?
Not the way you're trying it. You're confusing compile time and run time, i.e.:
- Generics are a pure compile time concept in Java. In fact, the generic type is removed during compilation (that's called type erasure). It only exists to give you type safety before compilation, meaning while writing your code.
- But the instance
type
is only assigned at run time. And because you don't know its type during compile time, you had to use a wildcard generic for it. So you only know the type, when you're executing your code.
So you can see that you can't use the information you gathered while executing your code to help you write it.
I highly recommend you read Oracle's tutorial on generics.
Part II
would I need to write out the methods for each individual class case?
I'm with Paul on this. I'm sure we can help you but you should give us an idea of what you're trying to accomplish.
...
Based on on your comment, I think the following would be a good solution.
Your model of the reality consists of continents, countries and cities. Hence you should have classes Continent
, Country
and City
. Since you're modeling population, all of them should have a method getPopulation()
. And this is one thing they have in common; all of those things are populated. The way to address this common structure / behavior in Java is to create an interface (let's call it Populated
) with a method getPopulation()
and have all of those classes implement it:
public interface Populated {
int getPopulation();
}
public class Country implements Populated {
@Override
public int getPopulation() {
...
}
}
// same for Continent and City
Now you have three classes but they can all be treated as one thing, as being populated. For example you can collect them in a list:
List<Populated> populated = new ArrayList<>();
populated.add(new Country());
populated.add(new City());
...
And this list can be sorted with a comparator which works for instances of Populated
:
public class PopulationComparator implements Comparator<Populated> {
public int compare(Populated left, Populated right) {
return left.getPopulation() - right.getPopultion();
}
}