Java 为什么定义接口,我们不定义什么id';I don’我不想用,还有别的办法吗?
公共接口人{ 公共无效冰毒()Java 为什么定义接口,我们不定义什么id';I don’我不想用,还有别的办法吗?,java,date,datetime,Java,Date,Datetime,公共接口人{ 公共无效冰毒() }实现此接口和实现此方法的每个类都将返回不同的值。因此,对于不同的类,您将有不同的方法实现。通过这种方式,您可以将所需结果返回给调用此方法的方法。如果您有一个抽象类要重写此方法,并将结果返回给调用它的方法,这也会对您有所帮助。接口允许您定义一组类通用的方法。对于每个类,接口的实现可能是不同的,由这些类独立实现方法的功能 interface Animal { // Define the interface Boolean canBite(); }
}实现此接口和实现此方法的每个类都将返回不同的值。因此,对于不同的类,您将有不同的方法实现。通过这种方式,您可以将所需结果返回给调用此方法的方法。如果您有一个抽象类要重写此方法,并将结果返回给调用它的方法,这也会对您有所帮助。接口允许您定义一组类通用的方法。对于每个类,接口的实现可能是不同的,由这些类独立实现方法的功能
interface Animal {
// Define the interface
Boolean canBite();
}
class Dog implements Animal {
// Define an implementation for Dog
@override
public Boolean canBite() {
return true;
}
}
class Duck implements Animal {
// Define an implementation for Duck
@override
public Boolean canBite() {
return false;
}
}
class Program {
public static void main(String[] args) {
// Create an array of the interface type and populate it with examples
Animal[] animals = new Animal[4];
animals[0] = new Dog();
animals[1] = new Duck();
animals[2] = new Duck();
animals[3] = new Dog();
// Check which members can bite
for (Animal animal : animals) {
System.out.println(animal.canBite());
}
}
}
/*
* Output:
* true
* false
* false
* true
*/
类Duck实现了Animal{@Override Public boolean canBite(){return false}}#andrew2111 Duck类返回false,通常类具有false的东西。它有什么用。你能给出一个例子吗?在Duck类中,重写了将false返回给类的方法????如果我不做类的对象,那么这个方法有什么用?我不确定我是否理解你的问题。你能告诉我更多的细节吗?如果不创建类的对象(实例),则无法访问这些方法。静态方法是从类访问的,但实例方法是从返回布尔值的Object.duck类访问的,对吗?我可以在创建类的对象时使用该布尔值??正当正如您给出的示例所示,打印值。这是正确的,Duck类在类型为Animal时返回false,因为您创建了Duck。