Ilan Aizelman WS Ilan Aizelman WS -4 years ago 89
Java Question

Should I make 'count' as static in derived class, how to access it

I have a class, lets say CargoShip, which is a derived class of 'Starcraft', which implements the interface IStarcraft.

This is the function that should return the count (number of instances) of every ship:

public static void printInstanceNumberPerClass (ArrayList<ISpacecraft> fleet){}

There's a solution which I thought of and I'm sure it will work, declaring 'getCount()' in ISpacecraft, then overriding it in each SpaceCraft ship (I have 4 ships), and just iterating through everyone of them, polymorphism.
Fine, I got that. but because the function is static (yes, I know we dont need to create an object to use it) I thought it might tell me something different. What do I mean by that? Is it possible to create 'static count = 0' instead, in every ship, and somehow access it?

The question is then, how can I access that static field when I get an arraylist of ISpacecraft objects?

Answer Source

Polymorphism doesn't work with static methods, method resolution is very different. For virtual methods on an instance the code may be referring to the object with a variable typed as a superclass or interface, and calling a method is resolved at runtime without your application code needing to know the exact concrete type. For static methods you call it on a specific class and if the method isn't found then it's called on a superclass. Your code has to start with some subclass and resolution works up the hierarchy from there. For static methods you can't not know a low-level class to call the method on, the way you can with instance methods on objects. You can't have the level of abstraction you take for granted with objects.

The comment by markspace provides a much better alternative. Use static methods for stateless functions like java.lang.Math.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download