What are 3 possible situations in which static methods might be included in classes?
I got this question for homework, and all开发者_高级运维 I can think of is to return a subclass of an abstract superclass.
Thanks!
Try looking at the existing Java APIs (eg: java.lang
and java.util
) to see where they use static methods.
Factory methods
- That return a particular instance like in a Singleton:
java.lang.Runtime.getRuntime()
- That return a subclass of a super class as you mentioned:
java.util.Calendar.getInstance()
- That perform type conversion:
String.valueOf(int)
Utility methods
- In a class that also has instance methods :
java.lang.String.format()
- In utility classes that are not meant to be instantiated at all:
java.util.Arrays
,java.lang.Math
,java.util.Collections
.
Generally methods which need not be tied to a specific object.
Factory methods.
Dont forget about using them to kick off the console applications we all had to write in cs101
精彩评论