-2

I recently saw implementing where a interface is implemented in a class and in another class we have a static final variable of the interface type and it somehow was able to complete computation from the class that had implemented the interface .

My question is how will the interface variable handle this if more than one class has a implementation of the interface. Am I missing something or it is just guessing where the implementation of interface is .

This is for java language

public interface DemoMe{
  public void doSomething();
}

public class MainClass implements demoMe {
   public void doSomething(){
     System.out.println("Something was done ");
   }
}

public class AnotherClass { 
  private final DemoMe demoVariable;

  public void useMe(){
    demoVariable.doSomething();
   }
}

here the AnotherClass somehow knows how to look for implementation of doSomething. can someone point me towards how this exactly works.

Praveen
  • 101
  • 14

1 Answers1

0

The variables in java interface are public static and final type. You whenever a class implements an interface. The interface variable become part of the class. Now these variable can be accessed using class reference or object reference. These variable are final so cannot be updated and static so always belong to the class. The interface itself need not to manage anything. The implementing class will take care of it.

Here we have defined an interface DemoMe with one method and one variable. Now DemoMeOne class implements the interface. The need to provide the definition for methods coming from interface. The doSomething() method simply prints a statement an access the variable from interface. Now we define an other class which instantiate the DemoMeOne class and access the interface method and variable.

interface DemoMe{
  public void doSomething();
  public int variable = 100;
}

class DemoMeOne implements DemoMe {
  public void doSomething(){
    System.out.println("Something was done.");
    System.out.println("Access interface variable: " + variable);
  }
}

class MainClass {
  public static void main(String[] args) {
    DemoMeOne demoMeOne = new DemoMeOne();
    System.out.println("Variable from interface using DemoMeOnce class: " + DemoMeOne.variable);
    System.out.println("Variable from interface using DemoMeOnce object reference: " + demoMeOne.variable);
    System.out.println("Variable from interface using interface itself: " + DemoMe.variable);
    demoMeOne.doSomething();
  }
}

output:
Variable from interface using DemoMeOnce class: 100
Variable from interface using DemoMeOnce object reference: 100
Variable from interface using interface itself: 100
Something was done.
Access interface variable: 100

YoungHobbit
  • 13,254
  • 9
  • 50
  • 73