Java 继承示例:电话、手机、固定电话
以下是用JAVA语言编写的代码,体现了电话、移动电话和固定电话之间的继承关系:\n\njava\nclass Phone {\n private String brand;\n private String number;\n \n public Phone(String brand, String number) {\n this.brand = brand;\n this.number = number;\n }\n \n public void call() {\n System.out.println("正在拨打电话...");\n }\n \n public void answer() {\n System.out.println("正在接听电话...");\n }\n}\n\nclass MobilePhone extends Phone {\n public MobilePhone(String brand, String number) {\n super(brand, number);\n }\n \n @Override\n public void call() {\n System.out.println("正在使用手机打电话...");\n }\n \n @Override\n public void answer() {\n System.out.println("正在使用手机接听电话...");\n }\n \n public void receiveMessage() {\n System.out.println("正在接收短信...");\n }\n}\n\nclass LandlinePhone extends Phone {\n public LandlinePhone(String brand, String number) {\n super(brand, number);\n }\n \n @Override\n public void call() {\n System.out.println("正在使用固定电话打电话...");\n }\n \n @Override\n public void answer() {\n System.out.println("正在使用固定电话接听电话...");\n }\n \n public void connectBroadband() {\n System.out.println("正在接入宽带...");\n }\n}\n\nclass PhoneFactory {\n public void testPhone(Phone p) {\n p.call();\n p.answer();\n }\n \n public Phone getPhone(int type) {\n if(type == 1) {\n return new LandlinePhone("固定电话", "123456789");\n } else if(type == 2) {\n return new MobilePhone("移动电话", "987654321");\n } else {\n return new Phone("电话", "111111111");\n }\n }\n}\n\npublic class Main {\n public static void main(String[] args) {\n PhoneFactory factory = new PhoneFactory();\n \n Phone phone1 = factory.getPhone(1);\n factory.testPhone(phone1);\n ((LandlinePhone)phone1).connectBroadband();\n \n Phone phone2 = factory.getPhone(2);\n factory.testPhone(phone2);\n ((MobilePhone)phone2).receiveMessage();\n \n Phone phone3 = factory.getPhone(3);\n factory.testPhone(phone3);\n }\n}\n\n\n代码中,Phone类是电话的基类,MobilePhone类和LandlinePhone类分别继承自Phone类,分别代表移动电话和固定电话。PhoneFactory类是电话厂类,其中的testPhone方法用于测试电话的打电话和接电话方法,getPhone方法用于根据传入的类型生成对应的电话对象。在Main类中,我们通过PhoneFactory对象生成了不同类型的电话,并对其进行了测试。
原文地址: https://www.cveoy.top/t/topic/pWib 著作权归作者所有。请勿转载和采集!