酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

class sunflower extends plant{ △ 8 public void show( ){ 9 system.out.println("向日葵"); 10 } 11}12 13 class nut extends plant{ 14 public void show( ){ 15 system.out.println("坚果墙"); 16 17}18 19 class pea extends plant{ 209 public void show( ){ 21 system.out.println("豌豆射手"); 22 } 23 }24 25 class plantfactory{ 26 public static plant creat(string s){ 27 if("向日葵".equalsignorecase(s)){ 28 return new sunflower(); 29 }else if("坚果墙".equalsignorecase(s)){ 30 return new nut(); 31 }else if("豌豆射手".

It looks like you have a Java code snippet that defines a factory pattern for creating different types of plants. However, there are a few issues and missing parts in the code. I'll help you correct and complete it. Here's the corrected and completed version: ```java class Plant { public void show() { System.out.println("这是一个植物"); } } class Sunflower extends Plant { @Override public void show() { System.out.println("向日葵"); } } class Nut extends Plant { @Override public void show() { System.out.println("坚果墙"); } } class Pea extends Plant { @Override public void show() { System.out.println("豌豆射手"); } } class PlantFactory { public static Plant create(String s) { if ("向日葵".equalsIgnoreCase(s)) { return new Sunflower(); } else if ("坚果墙".equalsIgnoreCase(s)) { return new Nut(); } else if ("豌豆射手".equalsIgnoreCase(s)) { return new Pea(); } else { return new Plant(); } } } public class Main { public static void main(String[] args) { Plant sunflower = PlantFactory.create("向日葵"); Plant nut = PlantFactory.create("坚果墙"); Plant pea = PlantFactory.create("豌豆射手"); sunflower.show(); nut.show(); pea.show(); } } ``` Explanation: 1. Plant Class: This is the base class with a default `show` method. 2. Sunflower, Nut, Pea Classes: These are subclasses of `Plant` and override the `show` method to display their specific names. 3. PlantFactory Class: This class contains a static method `create` that takes a string parameter and returns an instance of the corresponding plant class. 4. Main Class: This class contains the `main` method to demonstrate the usage of the factory pattern. Key Points: - Inheritance: Each plant subclass inherits from the `Plant` class. - Polymorphism: The `show` method is overridden in each subclass to provide specific behavior. - Factory Method: The `create` method in `PlantFactory` uses conditional logic to return the appropriate plant object based on the input string. This should work correctly and print the names of the plants when run. [2024-10-17 17:03:51 | AI写代码神器 | 498点数解答]

相关提问