Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block an interface to be extended [duplicate]

As since in a class I can do:

public final class Foo{}

wich means no more classes can extends that Foo class... e.g. String class is final, so no custom class can extends the class String.

How can I prevent to do the same with an interface?

If I do

public interface ISome{
    void fly();
}

I would like to allow that

class A implements ISome {}

but block that

public interface IHouse extends ISome{
    void fly();
}

doing this

public final interface ISome{}

makes no sense... and will bring a compile error like:

Illegal modifier for the interface
like image 981
ΦXocę 웃 Пepeúpa ツ Avatar asked Dec 06 '25 07:12

ΦXocę 웃 Пepeúpa ツ


1 Answers

You can't.

Supposedly the Java designers didn't think there would ever be an appropriate use case for this: if you don't want an interface to be extended then really you ought to declare those functions directly in a concrete class.

That said, you can achieve this in C++ as in this language an interface is more of a convention - consisting of only pure virtual functions, and you can enforce non-extensibility with techniques such as friendship.

like image 114
Bathsheba Avatar answered Dec 07 '25 21:12

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!