如何删除运算符“instanceof”并用多态替换它?NamedPlace 和 DescribedPlace 都是主类 Place 的子类。
class RightClickListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent mev) {
p = (Place) mev.getSource();
if (mev.getModifiers() == InputEvent.BUTTON3_MASK) {
if (p instanceof NamedPlace) {
JOptionPane.showMessageDialog(null, p.getName() + " " + p.getPosition(), "Platsinfo: ", JOptionPane.INFORMATION_MESSAGE);
}
if (p instanceof DescribedPlace) {
JOptionPane describedPane = new JOptionPane();
describedPane.setMessage("Name: " + p.getName() + " " + p.getPosition() + "\n" + "Description: " + ((DescribedPlace) p).getDescription());
describedPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
JDialog dialog = describedPane.createDialog(p, "Platsinfo:");
dialog.setVisible(true);
}
}
}
}
慕森王
相关分类