当前位置:网站首页>Interface as a parameter (interface callback)

Interface as a parameter (interface callback)

2022-07-07 08:22:00 Cold_ Chuan

interface Animal {
    
    void eat();
}


@Slf4j
class Cat implements Animal {
    
    
    @Override
    public void eat() {
    
        log.debug(" Cats eat fish ");
    }
}

@Slf4j
class Dog implements Animal {
    
    @Override
    public void eat() {
    
        log.debug(" Dogs eat meat ");
    }
}

class AnimalTest {
    
	// Interface as a parameter 
    public void AnimalEat(Animal animal) {
    
        animal.eat();
    }
}

Realization

@Test
    public void interfaceCallbackTest(){
    
        Animal1 cat = new Cat(); //Cat Class implements the Animal1, be Animal1 Point to Cat Object address of class 
        Animal2 dog = new Dog(); //Dog Class implements the Animal2, be Animal2 Point to Dog Object address of class 
        AnimalTest animalTest = new AnimalTest();
        animalTest.AnimalEat(cat); //  It's actually calling theta cat Of eat() Method   Cats eat fish 
        animalTest.AnimalEat(dog); //  It's actually calling theta dog Of eat() Method   Export dogs to eat meat 
    }

Animal1 cat = new Cat(); The so-called interface callback , namely Which class implements it , It points to the object address of which class
animalTest.AnimalEat(cat); The animal interface finds the address of the cat's object , Call the cat's eating method

原网站

版权声明
本文为[Cold_ Chuan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070519398673.html