用Java编写全面的程序,其中包括OOP的所有共同特征,并使用以下方法显示变量的结果
时间: 2024-04-09 11:28:02 浏览: 14
当然可以!下面是一个使用Java编写的示例程序,其中包括OOP的所有共同特征,并使用方法显示变量的结果:
```java
public class OOPExample {
private int num; // 私有变量
// 构造方法
public OOPExample(int num) {
this.num = num;
}
// 公有方法
public int getNum() {
return num;
}
// 静态方法
public static void printMessage(String message) {
System.out.println(message);
}
// 继承
public static class ChildClass extends OOPExample {
public ChildClass(int num) {
super(num);
}
}
// 多态
public interface Animal {
void sound();
}
public static class Dog implements Animal {
@Override
public void sound() {
System.out.println("汪汪汪!");
}
}
public static class Cat implements Animal {
@Override
public void sound() {
System.out.println("喵喵喵!");
}
}
public static void main(String[] args) {
OOPExample example = new OOPExample(10);
System.out.println("私有变量的结果:" + example.getNum());
printMessage("静态方法的结果:Hello World!");
Animal dog = new Dog();
Animal cat = new Cat();
dog.sound();
cat.sound();
}
}
```
这个示例程序展示了Java中的封装(私有变量)、继承(子类)、多态(接口和实现类)以及静态方法的特性。在`main`方法中,我们创建了一个`OOPExample`对象,并通过`getNum`方法获取私有变量的值。然后,使用`printMessage`静态方法打印一条消息。最后,我们使用多态创建了一个`Animal`接口的实现类`Dog`和`Cat`,并调用它们的`sound`方法显示不同的结果。
请注意,这只是一个简单的示例程序,用于演示OOP的常见特征。在实际应用中,你可以根据需求设计更复杂的程序结构。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)