简体   繁体   中英

Implementing an interface without implementing it

Can implement an interface without implementing it-- as in:

interface A { void m2(); }

class B { public void m2() { ... } } 

class C extends B implements A { ... /* no implementation of m2() here */ } 

What i'm wondering is, is there a way to force the descendant class, class C here, to implement the method m2() ?

This looks a bit sideways-- breaking the expected chain in inheritance.

There can be cases i can't think of now where it would be necessary to force the subclass in this fashion.

TIA.

//==========================

EDIT: one scenario:

There is a class B and an interface A developed in two different places in the application with a method m2() having the same signature in both.

B is implementing m2() in its own way-- without even knowing what A is all about.

when C above gets quickly in, it has an m2() that has nothing to do with the contract in A .

This takes poor management of development. but, still.

//=================================

EDIT-2:

Restricting m2()-of-B's access to package level or protected works. This way, m2() of B that C is inheriting won't do for that of A since it isn't public .

This is a bit of tempering with what a class should do in itself-- but then it isn't. A super-class should be able to direct a sub this much. loosely similar to the use of final on methods or on the class itself. Note AndyThomas's useful ans. though.

As written, class C must satisfy both the contracts for B.m2() and A.m2() .

Those contracts are either compatible or not.

If those contracts are compatible, then B.m2() is either a sufficient implementation for C or not.

  • If it is sufficient, an override is not required.
  • If it is not sufficient, then it is the responsibility of class C to override it.
    • Inside class C, you can force an override by ... simply overriding the method.
    • Outside class C, you cannot force C to override an existing, non-abstract superclass method.

If those contracts are not compatible, then C cannot both extend B and implement A. In this case, you could use composition instead of inheritance -- have C implement A, and include a B in its representation.

There is no mechanism in Java to force all instantiable classes implementing an interface to override superclass implementations of methods in the interface. You can, however, force all instantiable classes to implement an abstract method somewhere in their inheritance hierarchy.

如果将类B声明为抽象类,则不需要实现m2,因此需要C(通过继承B)来执行以下操作:

abstract class B implements A {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM