简体   繁体   中英

Java interface concept

When you build and interface, how many classes can implement the interface?
If the answer is more than one, then how does java know which implementations to use when you make the call to the interface(not calling the implementation directly)?

how many classes can implement the interface?

As many as you need.

If the answer is more than one, then how does java know which implementations to use when you make the call to the interface(not calling the implementation directly)?

Here helps knowledge about late binding (also known as dynamic binding).

Lets say that you have interface and classes which implement it like

interface Animal{
    void makeSound();
}

class Cat implements Animal{
    public void makeSound(){
        System.out.println("mew");
    }
}

class Dog implements Animal{
    public void makeSound(){
        System.out.println("woof");
    }
}

You also have code like

Animal a1 = new Cat();
Animal a2 = new Dog();

a1.makeSound();
a2.makeSound();

Result which you will see is

mew
woof

It happens because body/code of method .makeSound() is being looked for (and invoked) at runtime (not compilation time). It is possible because each object remembers its class, so object held by a1 reference knows that it is instance of Cat and object held by a2 is instance of Dog .

So in short when you do:

a1.makeSound();
  • JVM takes object which a1 holds,
  • then asks that object about its class (in this case it will learn that it is instance of Cat class),
  • then it will accesses that class ( Cat.class file) and is searching for code of makeSound() (if such method will not be found, then it will assume it must been inherited it will try to search it in superclass)
  • and when it will find this method it will invoke code from it.

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