Java多態(tài)性是一種強(qiáng)大的特性,它允許我們編寫更加靈活和可擴(kuò)展的代碼。在Java中,多態(tài)性主要通過接口和繼承來實(shí)現(xiàn)。要應(yīng)對(duì)變化,我們可以利用以下方法:
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多態(tài)性應(yīng)對(duì)變化,我們需要編寫靈活、可擴(kuò)展和可維護(hù)的代碼。通過使用接口、抽象類和依賴注入等設(shè)計(jì)模式和技巧,我們可以輕松地應(yīng)對(duì)需求變化。