Pushkar
Pushkar

Reputation: 339

How to implement a function in a class which may or may not be over-ridden in sub class?

Currently there is a class say A, which has final method say mainMethod() and it calls three methods a(), b() and c(). Now, the child class has to implement a and b so I made them abstract. But c may not be needed. How do I achieve it? I am using PHP.

Upvotes: 0

Views: 45

Answers (1)

Mario A
Mario A

Reputation: 3363

Just create an empty non-abstract method and in the comments describe that it may be overwritten. E.g:

abstract class A 
{
    public abstract function a();
    public abstract function b();

    /**
     * This method may be overwritten for purpose X ...
     */
    public function c() 
    {
        /* empty */
    }
}

This way you can call c(), and it may or may not have any function. The inheriting class is forced to implement a() and b(), and can optionally overwrite c(). A good php editor like NetBeans or whatever is capable of code hinting, where also the comment will be shown, so the programmer is informed about the purpose of the function.

Upvotes: 1

Related Questions