How to make a class accept different type of child classes (of another parent class) in the constructor in java

huangapple 未分类评论53阅读模式
英文:

How to make a class accept different type of child classes (of another parent class) in the constructor in java

问题

我目前在努力解决这个问题所以请对我温柔一点因为我对这一切还很陌生

我有一个名为Player的类其中一个参数是Location然而现在我遇到了一个问题我不太确定如何解决我创建了多个Location的子类比如HotelRoom和HotelKitchen我需要能够从创建的Player对象中访问子类中的方法

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

Player类

...

Location类

...

一个Location的子类示例

...

以下是我的ApplicationTester类其中包含main方法中的一个方法用于创建一个位置对象然后将其设置为参数

...

allItemsnumber方法用于上面的方法

...

现在我看到有些人建议使用接口/抽象类感谢您的建议但出于两个原因我还是有些困惑

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

最后与上面类似的情况如果位置被设置为抽象类Player的构造函数是否接受Location的任何子类
英文:

I am struggling a lot with this so do go easy on me please as I am still new to all of this.

I have a class called Player and one of the parameters it takes is a Location. However, I have now run into a issue which I am not to sure how to solve. I have made multiple child classes of Location, like HotelRoom and HotelKitchen, and I need to be able to access the methods in the child classes from the a created Player object .

Now I can not just change the Player's constructor to accept HotelRoom as the characters location might change to HotelKitchen.

Player Class:

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;
}
}

Location Class

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;
}

One of locations child classes

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;
} 
}

Below is a method in my ApplicationTester class (which has the main) that creates a location object to then set as a paramater

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;

}

The allitems(number) method which is used by the method above

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
    }
}

Now I see some people are suggesting interfaces/abstract classes and I thank you for the input but still confused for two reasons.

Firstly, the method in main called setLocation can only return a location, now once location is made Abstract will it allow me to return any class that is a child of location?

Lastly, similar situation as above. If location is made Abstract, would the Player constructor accept any child class of location?

huangapple
  • 本文由 发表于 2020年3月15日 16:43:52
  • 转载请务必保留本文链接:https://java.coder-hub.com/60691099.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定