首页 > 解决方案 > 如何使一个类在java的构造函数中接受不同类型的子类(另一个父类)

问题描述

我为此苦苦挣扎,所以请放轻松,因为我对这一切还很陌生。

我有一个名为 Player 的类,它采用的参数之一是 Location。但是,我现在遇到了一个我不确定如何解决的问题。我已经创建了多个 Location 子类,例如 HotelRoom 和 HotelKitchen,并且我需要能够从创建的 Player 对象访问子类中的方法。

现在我不能只更改 Player 的构造函数以接受 HotelRoom,因为角色位置可能会更改为 HotelKitchen。

玩家等级:

public class Player {
    private int health;
    private int cluesLeft; //1 clue per level 
    private String name;
    private Location currentRoom;

public Player(String name, int health, int cluesLeft, Location currentRoom) {
    this.setHealth(health); 
    this.setCluesLeft(cluesLeft);
    this.setName(name);
    this.setCurrentRoom(currentRoom);
}

/**
 * @return the health
 */
public int getHealth() {
    return health;
}

/**
 * @param health the health to set
 */
public void setHealth(int health) {
    this.health = health;
}

/**
 * @return the cluesLeft
 */
public int getCluesLeft() {
    return cluesLeft;
}

/**
 * @param cluesLeft the cluesLeft to set
 */
public void setCluesLeft(int cluesLeft) {
    this.cluesLeft = cluesLeft;
}

/**
 * @return the name
 */
public String getName() {
    return name;
}

/**
 * @param name the name to set
 */
public void setName(String name) {
    this.name = name;
}   

/**
 * @return the currentRoom
 */
public Location getCurrentRoom() {
    return currentRoom;
}

/**
 * @param currentRoom the currentRoom to set
 */
public void setCurrentRoom(Location currentRoom) {
    this.currentRoom = currentRoom;
}
}

位置类

import java.util.Scanner;

/**
 *
 * @author User
 */
public class Location {
    static Scanner scan = new Scanner(System.in);
    private String locationImage; // string holds the ASCII map
    private String locationName;
    private String[] itemImages;

public Location(String locationName, String locationImage, String[] itemImages) {
    this.setLocationName(locationName);
    this.setLocationImage(locationImage);
    this.setItemImages(itemImages);
}

/**
 * @return the locationImage
 */
public String getLocationImage() {
    return locationImage;
}

/**
 * @param locationImage the locationImage to set
 */
public void setLocationImage(String locationImage) {
    this.locationImage = locationImage;
}

/**
 * @return the locationName
 */
public String getLocationName() {
    return locationName;
}

/**
 * @param locationName the locationName to set
 */
public void setLocationName(String locationName) {
    this.locationName = locationName;
}

public void printLocationMap() {
    try {
        Thread.sleep(1500);
    } catch (Exception e) {
        System.out.print(e);
    }
    System.out.println(this.getLocationImage());
}

public String retrieveSpecificItem(int item){
    String[] array = this.getItemImages();

    for (int x = 0; x < array.length; x++) {
        if (item == (x + 1)) {
            return array[x];
        }
        else {
            return null;
        }
    }
    return null;
}

/**
 * @return the itemImages
 */
public String[] getItemImages() {
    return itemImages;
}

/**
 * @param itemImages the itemImages to set
 */
public void setItemImages(String[] itemImages) {
    this.itemImages = itemImages;
}

位置子类之一

import java.util.Scanner;

/**
 *
 * @author User
 */
public class HotelRoom extends Location {

Scanner scan = new Scanner(System.in);

public HotelRoom(String locationName, String locationImage, String[] itemImages) {
    super(locationName, locationImage, itemImages);

}

public static String instructions(Player gameCharacter) {
    boolean loopDone = false;
    String choice = "";

     do {
         String menu = "What would you like to do next?\n"+ 
                   "1.) Move to Kitchen\n"+ 
                   "2.) Inspect PC\n"+
                   "3.) Inspect Cupboard\n"+ 
                   "4.) Inspect bed\n"
                 + "5.) Guess who did it!";


    int userChoice = JavaApplication2.checkInput(menu);

    switch(userChoice) {
        case 1: 
            choice = "HotelKitchen";
            loopDone = true;
            break;
        case 2: 
            System.out.println(this.retrieveSpecificItem(0));
            break;
        case 3: 
            System.out.println(this.retrieveSpecificItem(1));
            break;
        case 4: 
           System.out.println(this.retrieveSpecificItem(2));
            break;
        case 5: 
            choice = "Choose";
            break;
     } 


}while (loopDone == false);

    return choice;
} 
}

下面是我的 ApplicationTester 类(具有主类)中的一个方法,它创建一个位置对象,然后将其设置为参数

public static Location setLocations(int whichRoom) {
    Location locations = null;


        String room = ("|----------|   [1]   |----------|\n"+
                      "| [CUPBOARD]             [PC]   |\n"+
                      "|               P               |\n"+
                      "|                               |\n"+
                      "|             [BED]             |\n"+
                      "|             |   |             |\n"+
                      "|             | X |             |\n"+
                      "|             |___|             |\n"+
                      "|-------------------------------|\n");

        String kitchen = ("|----------|   [1]   |----------|\n"+
                          "| [FRIDGE]              [OVEN]  |\n"+
                          "|               P               |\n"+
                          "|                               |\n"+
                          "|        [SERVING TABLE]        |\n"+
                          "|                               |\n"+
                          "|           [TABLES]            |\n"+
                          "|                               |\n"+
                          "|-------------------------------|\n");
        if (whichRoom == 1) {
            Location hotelRoom = new Location("Hotel Room", room, allItems(1));
            locations = hotelRoom;
        }
        else {
            Location hotelKitchen = new Location("Hotel Kitchen", kitchen, allItems(2));
            locations = hotelKitchen;
        }

        return locations;

}

上述方法使用的 allitems(number) 方法

public static String[] allItems(int area) {
        String pc = "\n" +
                    "             ____________________________________________________\n" +
                    "            /                                                    \\\n" +
                    "           |    _____________________________________________     |\n" +
                    "           |   |                 ___________________         |    |\n" +
                    "           |   |                |                   |        |    |\n" +
                    "           |   |   DuckDuckGo - |How to remove stain|        |    |\n" +
                    "           |   |                |___________________|        |    |\n" +
                    "           |   |                                             |    |\n" +
                    "           |   |                                             |    |\n" +
                    "           |   |                                             |    |\n" +
                    "           |   |   Removing stains from any surface          |    |\n" +
                    "           |   |                                             |    |\n" +
                    "           |   |   Getting rid of stains in 3 steps          |    |\n" +
                    "           |   |                                             |    |\n" +
                    "           |   |   Choosing the right stain remover          |    |\n" +
                    "           |   |                                             |    |\n" +
                    "           |   |_____________________________________________|    |\n" +
                    "           |                                                      |\n" +
                    "            \\\\_____________________________________________________/\n" +
                    "                   \\\\_______________________________________/\n" +
                    "                _______________________________________________\n" +
                    "             _-'    .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.  --- `-_\n" +
                    "          _-'.-.-. .---.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.--.  .-.-.`-_\n" +
                    "       _-'.-.-.-. .---.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-`__`. .-.-.-.`-_\n" +
                    "    _-'.-.-.-.-. .-----.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-----. .-.-.-.-.`-_\n" +
                    " _-'.-.-.-.-.-. .---.-. .-----------------------------. .-.---. .---.-.-.-.`-_\n" +
                    ":-----------------------------------------------------------------------------\n" +
                    "`---._.-----------------------------------------------------------------._.---";

    String cupboard = "     __________\n" +
                      "   /          /|\n" +
                      " /__________/  |\n" +
                      " |________ |   |\n" +
                      " /_____  /||   |\n" +
                      "|\".___.\"| ||   |\n" +
                      "|_______|/ |   |\n" +
                      " || .___.\"||  /\n" +
                      " ||_______|| /\n" +
                      " |_________|/\n"; 

    String bed = "                     __.--'|\n" +
                 "              ___.---'      |\n" +
                 "      ___.---'              |\n" +
                 " _.--'              \\\\\\     |\n" +
                 " |                  XX |    |\n" +
                 " |                  U. '    |\n" +
                 " J                  __=__   |\n" +
                 "  L               /          |\n" +
                 "  L              / /|.  .|     -`-.\n" +
                 "  |              | ||____|      __.>-._\n" +
                 "  |              | ||    |__.--'       `--._\n" +
                 "  J-._ _____.---------'                    `--.__\n" +
                 "  J   `-<_                                    `-.__\n" +
                 "   L      `-.                                     _>-.\n" +
                 "   +.        `-._                          ___.--'   |\n" +
                 "   | `-._        `-._                __.--'          |\n" +
                 "         `-._        `-.       __.--'            _.--'\n" +
                 "             `-._       `-._.-'             _.--'    |\n" +
                 "                 `-.       |           _.--'\n" +
                 "                    `-.    |      _.--'\n" +
                 "                       `-. | _.--'\n" +
                 "                          `|'\n" +
                 "                           |";

    String sink = "   ___\n" +
                  "                     .' _ '.\n" +
                  "                    / /` `\\ \\\n" +
                  "                    | |   [__]\n" +
                  "                    | |    {{\n" +
                  "                    | |    }}\n" +
                  "                 _  | |  _ {{\n" +
                  "     ___________<_>_| |_<_>}}________\n" +
                  "         .=======^=(___)=^={{====.\n" +
                  "        / .----------------}}---. \\\n" +
                  "       / /                 {{    \\ \\\n" +
                  "      / /                  }}     \\ \\\n" +
                  "     (  '========================='  )\n" +
                  "      '-----------------------------'";

    String couch = ".----.\n" +
                    "                  |    |\n" +
                    "                  |____|\n" +
                    "   _.-------------._()_.-------------._\n" +
                    "  / |             | )( |             | \\\n" +
                    "  | |             | () |             | |\n" +
                    "  _\\|_____________| )( |_____________|/_\n" +
                    ".=. /             /(__)\\             \\ .=.\n" +
                    "|U|/_____________/______\\_____________\\|U|\n" +
                    "| |====================================| |\n" +
                    "| |                                    | |\n" +
                    "|_|LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLlc|_|";

    String bin = " _.,-----/=\\-----,._\n" +
                 " (__ ~~~\"\"\"\"\"\"\"~~~ __)\n" +
                 "  | ~~~\"\"\"\"\"\"\"\"\"~~~ |\n" +
                 "  | |  ; ,   , ;  | |\n" +
                 "  | |  | |   | |  | |\n" +
                 "  | |  | |   | |  | |\n" +
                 "  | |  | |   | |  | |\n" +
                 "  | |  | |   | |  | |\n" +
                 "  | |  | |   | |  | |\n" +
                 "  | |  | |   | |  | |\n" +
                 "  | |  | |   | |  | |\n" +
                 "  |. \\_| |   | |_/ .|\n" +
                 "   `-,.__ ~~~ __.,-'\n" +
                 "         ~~~~~";

    String[] hotelRoom = {pc, cupboard, bed};
    String[] hotelKitchen = {bin, couch, sink};

    if (area == 1) {
        return hotelRoom;
    } else if (area == 2) {
        return hotelKitchen;
    } else if (area == 3) {
        return null; //not set up yet
    } else if (area == 4){
        return null; //not set up yet
    } else {
        return null; //not set up yet
    }
}

现在我看到有些人在建议接口/抽象类,我感谢您的输入,但由于两个原因仍然感到困惑。

首先,main 中的方法 setLocation 只能返回一个位置,现在一旦位置被抽象出来,它是否允许我返回任何位置的子类?

最后,与上述类似的情况。如果位置是抽象的,那么 Player 构造函数会接受位置的任何子类吗?

标签: javainheritanceconstructor

解决方案


推荐阅读