我有 2 个类。例如;矩形和圆形
public class Rectangle {
private int width;
private int height;
public Rectangle(int width,int height) {
this.width = width;
this.height = height;
}
public int getArea() {
return width * height;
}
}
public class Circle {
private int radius;
public Circle(int radius) {
this.radius = radius;
}
public int getArea() {
return radius * radius * 3;
}
}
而且我在类外有这个方法;
public void PrintArea(Object object) {
if(object instanceof Circle)
System.out.print(((Circle)object).getArea());
else if(object instanceof Rectangle)
System.out.print(((Rectangle)object).getArea());
}
但我想在没有类转换的情况下在一行上完成,例如:
public void PrintArea(Object object) {
System.out.print(object.getArea());
}
这可能吗?谢谢...(Circle 和 Rectangle 只是例子。我在大项目中有不同的详细类。我无法更改这个类结构)
最佳答案
您可以使用多态性在运行时调用正确实例的方法。为此,您可以创建一个具有 printArea()
方法的接口(interface) Shape
。此方法将由具体类 Rectangle
和 Circle
实现,它们将定义它们的特定行为:
interface Shape {
void printArea();
}
class Rectangle implements Shape {
private int width;
private int height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public int getArea() {
return width * height;
}
public void printArea() {
System.out.println(this.getArea());
}
}
class Circle implements Shape {
private int radius;
public Circle(int radius) {
this.radius = radius;
}
public int getArea() {
return radius * radius * 3;
}
public void printArea() {
System.out.println(this.getArea());
}
}
然后会有一个像 Printer
这样的调度程序类,它接受一个形状对象并调用它的 printArea()
方法:
class Printer {
public void printArea(Shape shape) {
shape.printArea();
}
}
然后你可以做这样的事情来使用 Java 中的动态方法分派(dispatch)概念:
public static void main(String[] args) {
Shape rectangle = new Rectangle(10, 20);
rectangle.printArea();
Shape circle = new Circle(20);
circle.printArea();
Printer printer = new Printer();
printer.printArea(circle);
printer.printArea(rectangle);
}
编辑
如果您不能在类中添加新方法,那么您可以使用从 Java 8 引入的 Shape
接口(interface)中的 default
方法:
interface Shape {
int getArea();
default void printArea(){
System.out.println(this.getArea());
}
}
现在假设您需要一个Square
实现,并且定义了getArea
,那么您不再需要定义一个printArea()
Square
类中的方法:
class Square implements Shape{
private int side;
public Square(int side) {
this.side = side;
}
public int getArea() {
return side * side;
}
}
这样,当您在现有类中实现新的 Shape
接口(interface)时,您就不会破坏现有的实现。
关于Java - 从方法返回不同的类并使用类的特定功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58128922/