Is it okay for a class to be marked as abstract if it has no abstract members? Even if there is no practical reason for to directly instantiate it? (aside from unit tests)
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- Sorting 3 numbers without branching [closed]
- How to maintain order of key-value in DataFrame sa
- Graphics.DrawImage() - Throws out of memory except
Short answer: yes.
Long answer: The
abstract
keyword marks a class and/or its members as not being useful directly. Why this may be varies from case to case; an abstract class may be too basic to do any real work, or it may have abstract members that are required to exist for other code in this class to work, but cannot be concretely defined at this level. The short of it is that by marking a class abstract, you tell the compiler and other developers not to instantiate this class directly, but instead to inherit from it to create a concrete useful implementation. You can do this even if the class has a working implementation for all its members, if you feel that the class must be inherited to make the best use of that implementation.Do you want that class to ever have an actual instance? If yes, then don't mark it abstract. If no, then mark it abstract.
If the goal is to make a base class that other classes will extend, it makes sense to make this an abstract class.
If, however, the goal is to make some form of Utility class -- one that has only
static
members -- the best way to handle this is to give the class a single constructor markedprivate
. That way, the class can not be instantiated, nor subclassed. This sends a clear signal that the only use of the class is to use itsstatic
methods. (This is a tip from Effective Java, by Josh Bloch)Yes, I think so. At least that's what I do from time to time ;-)
Yes, it is reasonable and beneficial to mark explicitly as abstract a base class that should not be instantiated -- even in the absence of abstract methods.