I have a JAVA class A which has a method foo
abstract class A {
abstract void foo();
}
I also have a derived class of A - MutableA. MutableA is a singleton object indicating that no update is necessary which is useful for reusing code flows. foo() should never be called on MutableA. What is the best way to achieve that:
Can someone recommend me what is the best practice in this case?
I would consider rethinking the design.
Having an abstract method in the super class implies that subclasses should implement that method. Unless you plan on having a larger hierarchy in which case you should consider moving the foo method lower down in the hierarchy closer to the implementation.
If you are intent on keeping the foo methods location I would make MutableA abstract as well.
You should consider havig a look at the Liskov substitution principle, which is one of the fundamental SOLID principles of good design.
The principle states that derived objects should not behave different than their parents. A common example for a violation of the Liskov principle is the derivation of a circle from an ellipse. Which is mathematically totally sensible and sound is considered to be bad design, for a circle derived from a ellipse would (for example) still expose the methods to set the width and the height, but it would behave oddly in some contexts. Consider the following
Something FooBar (Ellipse e)
{
// do something with e
}
If we did not know that a caller passed a Circle rather than an Ellipse and we set both the width and the height our results may differ from what we expect, since the Circle either ignored SetHeight or it sets the width bot on SetWidth and SetHeight. Either way this behavior is unexpected if we expected to operate on an Ellipse. Hence the Liskov substitution principle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With