Java/Android noob here (Still) I hoped you could help.
I was trying to add a small convenience method to get the number of time that has passed rather than the number of time since EPOCH.
So I tried to do this:
public class EasyLocation extends android.location.Location {
...
public long getElapsedTime() {
return getTime() - System.currentTimeMillis();
}
}
However when I tried to use it like in the code below which casts it to my Location class. I got a class cast exception. I’ve read up on it and I fully understand why it doesn’t work. That’s not the issue.
The issue is: it’s not a train smash but I would like to have what is returned to have my method on it to make the rest of my code a bit cleaner. I can’t figure out a way around it. Any ideas on how to do that?
lastNetworkLocation = (EasyLocation) locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Thanks,
Gerard.
You can’t do it like that. (A
Locationis not anEasyLocation.)I believe what you’re looking for is the decorator pattern.
You would typically do something like this:
And instead of doing
you do
Keep in mind though that most people would probably say “Favor composition over inheritance”, and go with