Java多態性是一種強大的特性,它允許我們編寫更加靈活和可擴展的代碼。在Java中,多態性主要通過接口和繼承來實現。要應對變化,我們可以利用以下方法:
public interface Animal {
void makeSound();
}
public class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
public class Cat implements Animal {
@Override
public void makeSound() {
System.out.println("Meow!");
}
}
public abstract class Shape {
private double x;
private double y;
public Shape(double x, double y) {
this.x = x;
this.y = y;
}
public abstract double area();
}
public class Circle extends Shape {
private double radius;
public Circle(double x, double y, double radius) {
super(x, y);
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
public class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double x, double y, double width, double height) {
super(x, y);
this.width = width;
this.height = height;
}
@Override
public double area() {
return width * height;
}
}
public interface MessageService {
void sendMessage(String message);
}
public class EmailService implements MessageService {
@Override
public void sendMessage(String message) {
System.out.println("Sending email: " + message);
}
}
public class SmsService implements MessageService {
@Override
public void sendMessage(String message) {
System.out.println("Sending SMS: " + message);
}
}
public class Notification {
private MessageService messageService;
public Notification(MessageService messageService) {
this.messageService = messageService;
}
public void notify(String message) {
messageService.sendMessage(message);
}
}
總之,要利用Java多態性應對變化,我們需要編寫靈活、可擴展和可維護的代碼。通過使用接口、抽象類和依賴注入等設計模式和技巧,我們可以輕松地應對需求變化。