Reklama
Pokazuje wyniki od 1 do 2 z 2

Temat: [Java] Użycie metod subklasy w klasie głównej

  1. #1

    Data rejestracji
    2009
    Posty
    313
    Siła reputacji
    15

    Domyślny [Java] Użycie metod subklasy w klasie głównej

    Na zaliczenie laborek podjąłem się napisania gry monopoly w Javie. Niestety napotkałem pewne problemy w dość prostej wydaje się rzeczy.

    Mianowicie, szkielet aplikacji wygląda póki co tak:
    Kod:
    public class Field {
        protected int fieldPosition;
        Field(){          
        }
    }
    Kod:
    public class Property extends Field{
        private String propertyGroup;
        private String propertyOwner;
        private String propertyName;
        private float propertyPrice;
        private boolean allowBuilding;
        private int numberOfHouses;
        private int numberOfHotels;
        private float basicValue;
        private float houseValue;
    
        final private int maxNumberOfHouses = 4;
        final private int getMaxNumberOfHotels = 1;
    
        public Property(int fieldPosition, String propertyGroup, String propertyName, float propertyPrice, float basicValue, float houseValue){
            this.fieldPosition = fieldPosition;
            this.propertyGroup = propertyGroup;
            propertyOwner = "none";
            this.propertyName = propertyName;
            this.propertyPrice = propertyPrice;
            allowBuilding = false;
            this.basicValue = basicValue;
            this.houseValue = houseValue;
            numberOfHotels = 0;
            numberOfHotels = 0;
        }
    
        /*
        Setters
         */
        public void setAllowBuilding(boolean allowBuilding) {
            this.allowBuilding = allowBuilding;
        }
    
        public void setPropertyOwner(String propertyOwner) {
            this.propertyOwner = propertyOwner;
        }
    
        /*
        Getters
         */
    
        public String getPropertyGroup() { return propertyGroup; }
    
        public String getPropertyOwner() {
            return propertyOwner;
        }
    
        public String getPropertyName() {
            return propertyName;
        }
    
        public float getPropertyPrice() {
            return propertyPrice;
        }
    
        public boolean isAllowBuilding() {
            return allowBuilding;
        }
    
        public int getNumberOfHouses() {
            return numberOfHouses;
        }
    
        public int getNumberOfHotels() {
            return numberOfHotels;
        }
    
        public int getMaxNumberOfHouses() {
            return maxNumberOfHouses;
        }
    
        public float getBasicValue() {
            return basicValue;
        }
    
        public float getHouseValue() {
            return houseValue;
        }
    
    
    
        /*
             Add and remove house and hotel methods
             */
        public void addHouse(){
                this.numberOfHouses = getNumberOfHouses() + 1;
                this.propertyPrice = getPropertyPrice() + 100;
        }
    
        public void removeHouse(){
                this.numberOfHouses = getNumberOfHouses() - 1;
                this.propertyPrice = getPropertyPrice() - 100;
        }
    
        public void addHotel(){
                this.numberOfHotels = getNumberOfHotels() + 1;
                this.propertyPrice = getPropertyPrice() + 400;
        }
    
        public void removeHotel(){
                this.numberOfHotels = getNumberOfHotels() - 1;
                this.propertyPrice = getPropertyPrice() - 400;
        }
    
        @Override
        public String toString() {
            return propertyName + getNumberOfHouses();
        }
    }
    Z klasy Field dziedziczyć będzie jeszcze kilka mniej złożonych klas jak Start, Idź do więzienia, Czerwona/Niebieska szansa, Property opisuje każdą rzecz którą można kupić.

    Następnie tworzę klasę Board, która defacto jest listą obiektów Field

    Kod:
    public class Board {
        Field board[] = new Field[40];
    
        public Board() {
            board[0] = new Start();
            board[1] = new Property(1,"Katowice","Mariacka", 600, 100, 175);
            board[2] = new Property(2, "Katowice","Stawowa", 750, 125, 215);
            board[3] = new Property(3, "Katowice","Korfantego", 1000, 150, 250);
        }
    
        public Field[] getBoard(){
            return board;
        }
    }
    A za akcje wykonywane w grze odpowiada klasa Game, w której mam min. metodę buyProperty
    Kod:
     public void buyProperty(Player player, Field property){
            if(player.getPlayerCash() >= property.getPropertyPrice() &&
                    (property.getPropertyOwner().equals("none"))){
                player.addProperty(property);
                property.setPropertyOwner(player.getPlayerName());
                player.removeCash(property.getPropertyPrice());
            }
        }
    Cannot resolve method 'getPropertyPrice()'
    Tutaj właśnie pojawia się problem, w metodzie buyProperty jako 2gi parametr muszę dać obiekt klasy Field, podczas gdy metody w środku, jak getPropertyPrice pochodzą z klasy Property. Przypominam, że Property dziedziczy po Field, więc nie mogę użyć metod Property w Field. Przesunięcie atrybutow i metody getPropertyPrice wyżej (tzn. do głównej klasy) niby powinno pomóc, ale nie potrzeba mi w klasie Field takich danych, bo ta klasa ma rozszerzać również pola które żadnej ceny nie mają.

    Na koniec pokazuje jak chce się odwołać do wspomnianej metody by wszystko było jasne
    Kod:
    public static void main(String[] args) {
            Board gameBoard = new Board();
            Game game = new Game();
            Player johny = new Player("Johny");
            game.buyProperty(johny, gameBoard.getBoard()[1]);        
        }
    Pytanie czy da się to jakoś sprytnie obejść czy cała aplikacja jest źle zaplanowana i dlatego takie coś wyszło?
    Ostatnio zmieniony przez hefalump : 08-01-2017, 19:35

  2. #2
    Avatar Rollercoster
    Data rejestracji
    2011
    Wiek
    29
    Posty
    1,247
    Siła reputacji
    14

    Domyślny

    Protip: używaj lomboka

    Pierwsze rozwiązanie z użyciem instance of:

    Kod:
        public void buyProperty(Field field){
            if (field instanceof Property) {
                Property property = (Property)field;
                property.getPropertyPrice();
            } else {
                //do nothing as field is not Property
                return;
            }
        }
    Drugie rozwiązanie już imo lepsze, zauważ że prawdopodobnie każde pole będzie musiało zrobić coś i na sobie i na użytkowniku(tutaj użytkownik to po prostu string dla ułatwienia):
    Oprócz tego, twoja klasa main nie będzie miała 100 metod typu: buyProperty, goToJail itd. tylko każda klasa pochoda od Field będzie miała w sobie logike.
    Kod:
    public class Game {
        public void handle(String user, Field property) {
            property.handle(user);
        }
    }
    Kod:
    public abstract class Field {
        protected int fieldPosition;
        Field(){
        }
    
        public abstract void handle(String user);
    }
    Kod:
    public class Property {
        @Override
        public void handle(String user) {
            // buy property here
        }
    }

    Ew. Visitor patter, z tym że to przekazywanie usera jest IMO chujowe:

    Kod:
    public class Game {
    
        private GameVisitor gameVisitor = new GameVisitor();
        public void handle(String user, Field property) {
            property.handle(user);
        }
    }
    Kod:
    public interface Visitable {
        void accept(String user, GameVisitor gameVisitor);
    }

    Kod:
    public class Property {
        @Override
        public void accept(String user, GameVisitor gameVisitor) {
            gameVisitor.visit(user, this);
        }
    }
    Kod:
    public class GameVisitor {
    
        public void visit(String user, Property property) {
    
        }
    
        public void visit(String user, Field field) {
    
        }
    }
    Ostatnio zmieniony przez Rollercoster : 08-01-2017, 20:35

  3. Reklama
Reklama

Informacje o temacie

Użytkownicy przeglądający temat

Aktualnie 1 użytkowników przegląda ten temat. (0 użytkowników i 1 gości)

Podobne tematy

  1. Sprzedam Tibia.com.pl - GP, Tibia Coins, Ibot+ Wiele metod płatności !
    Przez bobciu w dziale Przedmioty
    Odpowiedzi: 37
    Ostatni post: 05-12-2017, 15:41
  2. Odpowiedzi: 5
    Ostatni post: 01-06-2015, 22:02
  3. League of Legends Najlepsze postacie w swojej klasie
    Przez Viedzmin w dziale Inne gry
    Odpowiedzi: 12
    Ostatni post: 22-05-2013, 21:11
  4. naganne w klasie maturalnej
    Przez Wujo w dziale Szkoła i nauka
    Odpowiedzi: 8
    Ostatni post: 24-12-2012, 12:42
  5. Zmiana szkoły w 2 klasie
    Przez Koksu w dziale Szkoła i nauka
    Odpowiedzi: 6
    Ostatni post: 07-11-2011, 19:43

Zakładki

Zakładki

Zasady postowania

  • Nie możesz pisać nowych tematów
  • Nie możesz pisać postów
  • Nie możesz używać załączników
  • Nie możesz edytować swoich postów
  •