写一个能够被不同实体作为入参的方法
时间: 2024-01-25 07:04:53 浏览: 25
好的,这是一个示例代码:
```java
public class EntityA {
private String name;
// getters and setters
public EntityA(String name) {
this.name = name;
}
}
public class EntityB {
private int age;
// getters and setters
public EntityB(int age) {
this.age = age;
}
}
public class SharedMethod {
public static void printInfo(Object entity) {
if (entity instanceof EntityA) {
EntityA entityA = (EntityA) entity;
System.out.println("Name: " + entityA.getName());
} else if (entity instanceof EntityB) {
EntityB entityB = (EntityB) entity;
System.out.println("Age: " + entityB.getAge());
} else {
System.out.println("Unknown entity type.");
}
}
}
```
在这个示例代码中,`EntityA` 和 `EntityB` 都是不同的实体类,它们都有自己的属性和构造方法。 `SharedMethod` 类中的 `printInfo()` 方法接受一个 `Object` 类型的参数 `entity`,并且根据 `entity` 的类型来打印不同实体的信息。 如果 `entity` 是 `EntityA` 类型的对象,则打印出名称信息;如果 `entity` 是 `EntityB` 类型的对象,则打印出年龄信息。这个方法可以被不同实体作为入参。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)