0

I am working on a Java project and want to understand the source code before implementing mine into it. The problem im facing is, how can the source code uses the abstract method from an interface without actually overriding it?

At first, I came to this statement: DeviceService deviceService = context.deviceService();

It is using 'context' to call the method deviceService(). Then, I went up to see where was 'context' being initialized. Then I found this: private final LinkDiscoveryContext context;

So, 'context' is a type of LinkDiscoveryContext. But then, 'LinkDiscoveryContext' is actually an interface. and the deviceService() is actually an abstract method without having any concrete definition of how the method should do.

I thought we cannot call the method of an interface unless we override it, but why is it working? I may be lack in developer knowledge in Java, and might have provided not enough information. But if the community has any guessing that could result in this working, please share with me.

Thanks in advance.

  • The source code can be found here: https://github.com/opennetworkinglab/onos/blob/fc25e87c54d09d575d452ee2ac21e19230e3eb26/providers/lldpcommon/src/main/java/org/onosproject/provider/lldpcommon/LinkDiscovery.java#L248 and here: https://github.com/opennetworkinglab/onos/blob/2b4de873e4033b7973b399d25cb8828a73bc2e24/providers/lldpcommon/src/main/java/org/onosproject/provider/lldpcommon/LinkDiscoveryContext.java#L55 – Desmond Kang Jun 29 '22 at 09:28
  • By the moment your code will reach `DeviceService deviceService = context.deviceService();` the field `private final LinkDiscoveryContext context;` has to be assigned to some spcific implementation so that the method would contain logic. – Alexey R. Jun 29 '22 at 09:28
  • ```context``` is assigned a value in the ```LinkDiscovery``` constructor, that variable will refer to an object whose class implements ```LinkDiscoveryContext```. This link may be useful for you to understand how it works: https://stackoverflow.com/questions/130794/what-is-dependency-injection – AddeusExMachina Jun 29 '22 at 09:33

1 Answers1

0

The class you mention has the constructor that takes instance of LinkDiscoveryContext as argument. So basically you assign a specific implementation to that field using class constructor.

Look for constructor usages to check where it is called from. Hence you will know from which place(s) does that implementation come.

Alexey R.
  • 8,057
  • 2
  • 11
  • 27