接口如何实例化呢?参照多态的方式,通过实现类对象实例化,这叫接口多态。多态的形式:具体类多态,抽象类多态,接口多态
时间: 2024-10-09 08:06:51 浏览: 53
接口在Java中不能直接实例化,因为它们只包含常量(static final变量)和抽象方法(没有具体实现)。然而,接口多态主要是通过接口引用来实现的。当你创建一个接口类型的引用并将其赋值给一个实现了该接口的具体类的对象时,就发生了接口多态。
例如:
```java
Interface Animal {
void makeSound();
}
Class Dog implements Animal {
public void makeSound() {
System.out.println("汪汪");
}
}
Class Cat implements Animal {
public void makeSound() {
System.out.println("喵喵");
}
}
// 这里是接口多态的示例
Animal animalRef; // 创建接口类型的引用
animalRef = new Dog(); // 实例化Dog并赋值给接口引用
animalRef.makeSound(); // 输出 "汪汪"
animalRef = new Cat(); // 另换实例为Cat
animalRef.makeSound(); // 输出 "喵喵"
```
在这个例子中,`animalRef`可以指向Dog或Cat的实例,体现了接口多态,无论它引用的是哪一个类,都会调用相应类中实现的makeSound方法。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044947.png)