Krishna Chaitanya
Krishna Chaitanya

Reputation: 438

How to restrict a subclass from overriding/implementing a superclass method

I have an abstract class with abstract method method1 and method2. I have classes A,B and C that extend abstract class.

My question is how do I restrict class B only from overriding method2? I want all other classes to be able to override any method by will.

If this is not possible using abstract classes, is it possible to implement such a case using interface? If so, could you please explain me with an example?

Here is one such case I want to implement. Abstract class bird has abstract method fly(). I want eagle to be able to override it but not the class penguin

    abstract class bird{
            abstract void fly();
    }
    class eagle extends bird{
            @override
            void fly(){
                    Sysout("I can fly really high!");
    }

    class penguin extends bird{
            @override
            /*How do I make sure this method is not at overridden, because there are chances that      this method could be accidentally overridden*/
            void fly(){
                    Sysout("I cannot fly");
            }
    }

Upvotes: 0

Views: 2362

Answers (2)

Phate
Phate

Reputation: 6612

You can't..you can either allow every subclass or no one. Just make an interface for the method you don't want to be implemented by B and make so that A and C implement this interface, while B just extends the abstact class.

Upvotes: 0

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

You could create a class in the middle of B and the super class that overrides method2 and marks it as final. Then, B will extend from this middle class and won't be able to override method2.

Note that in this case, it would be better to add behavior by using interfaces rather than extending methods. So, for example:

public interface CanFly {
    void fly();
}

public class Eagle implements CanFly {
    @Override
    public void fly() {
        //...
    }
}

public class Penguin {
    //I cannot fly, I do not need to implement CanFly
}

Upvotes: 5

Related Questions