java - Enforce method overload -
looking @ great example polymorphism vs overriding vs overloading , consider scenario:
abstract class human { public void gopee() { println("drop pants"); } } class male extends human { public void gopee() { super.gopee(); println("stand up"); } } class female extends human { public void gopee() { super.gopee(); println("sit down"); } }
my questions:
is possible, on concrete classes level, enforce using super.gopee() inside gopee() ? if - how ?
is possible, on abstract class level, know concrete class had called super.gopee() ? rationale if need call method let's
lifttoiletseat()
somewhere on abstract class level.
thank you.
you can enforce not giving subclass choice, using simple template method pattern. in superclass wants enforce call super
, don't give choice.
make method final
can't overridden, , call abstract protected
method must overridden. superclass behavior enforced.
abstract class human { public final void gopee() { system.out.println("drop pants"); tostandornottostand(); } protected abstract void tostandornottostand(); }
then subclass can't override superclass method, can't decide not call super
, must override abstract method concrete.
class male extends human { @override protected void tostandornottostand() { println("stand up"); } }
and female
can done similarly.
it possible know concrete class getclass()
method, doesn't make sense subclass-specific behavior in superclass. should able have lifttoiletseat
in male
subclass.
Comments
Post a Comment