2017-01-03 16 views
-1

В настоящее время я пытаюсь реорганизовать 2 подкласса в суперкласс. Подклассы называются Taxi и Shuttle, а суперкласс называется Vehicle. Я переместил повторяющийся код в обоих и сделал конструктор в подклассах вызова методы супер, как показано ниже, но я получаю сообщение об ошибкеНевозможно ссылаться на «X» до того, как конструктор супертипа был вызван сообщением об ошибке

не может ссылаться на «идент» перед супертипом конструктор был вызван)

Почему?

Вот Vehicle

public class Vehicle 
{ 
    // instance variables - replace the example below with your own 
    protected String ident; 
    // The Destination Of Taxi and Shuttle 
    protected String destination; 
    // The location of this shuttle. 
    protected String location; 

    /** 
    * Constructor for objects of class Vehicle 
    */ 
    public Vehicle(String id, String base) 
    { 
     // initialise instance variables 
     this.ident = id; 
     location = base; 
     destination = null; 
    } 

    /** 
    * Return the location of the shuttle. 
    * @return The location of the shuttle. 
    */ 
    public String getLocation() 
    { 
     return location; 
    } 

    /** 
    * Return the destination of the shuttle. 
    * @return The destination of the shuttle. 
    */ 
    public String getDestination() 
    { 
     return destination; 
    } 

    /** 
    * Return the ID of the shuttle. 
    * @return The ID of the shuttle. 
    */ 
    public String getIdent() 
    { 
     return ident; 
    } 

} 

Вот Taxi

public class Taxi extends Vehicle 
{ 
    // Whether it is free or not. 
    private boolean free; 

    /** 
    * Constructor for objects of class Taxi. 
    * @param base The name of the company's base. 
    * @param id This taxi's unique id. 
    */ 
    public Taxi(String id, String base) 
    { 
     super(ident); 
     free = true; 
    } 

    /** 
    * Book this taxi to the given destination. 
    * The status of the taxi will no longer be free. 
    * @param destination The taxi's destination. 
    */ 
    public void book(String destination) 
    { 
     setDestination(destination); 
     free = false; 
    } 

    /** 
    * Return the status of this taxi. 
    * @return The status. 
    */ 
    public String getStatus() 
    { 
     return vehicle.ident + " at " + location + " headed for " + 
     destination; 
    } 


    /** 
    * Indicate that this taxi has arrived at its destination. 
    * As a result, it will be free. 
    */ 
    public void signalArrival() 
    { 
     location = destination; 
     destination = null; 
     free = true; 
    } 
} 

Вот Shuttle

import java.util.ArrayList; 

/** 
* A shuttle. 
* Shuttles have a unique ID, a location and a list of destinations. 
* They operate a circular route. 
* 
* @author David J. Barnes 
* @version 2016.12.04 
*/ 
public class Shuttle extends Vehicle 
{ 

    private ArrayList<String> route; 
    // The destination number in route that the shuttle is 
    // currently headed for. 
    private int destinationNumber; 

    /** 
    * Constructor for objects of class Shuttle 
    * @param id This shuttle's unique id. 
    * @param route The route taken by this shuttle. 
    *    The first entry is the starting location. 
    */ 
    public Shuttle(ArrayList<String> route) 
    { 
     super(ident); 
     setRoute(route); 
    } 

    /** 
    * Return the status of this shuttle. 
    * @return The status. 
    */ 
    public String getStatus() 
    { 
     return ident + " at " + location + " headed for " + 
     destination; 
    } 


    /** 
    * Indicate that this shuttle has arrived at its next destination. 
    */ 
    public void signalArrival() 
    { 
     location = destination; 
     setNextDestination(); 
    } 

    /** 
    * Set the next destination of the shuttle. 
    */ 
    private void setNextDestination() 
    { 
     destinationNumber++; 
     if(destinationNumber >= route.size()) { 
      // End of the circular route. 
      // Start from the beginning again. 
      destinationNumber = 0; 
     } 
     setDestination(route.get(destinationNumber)); 
    } 

    /** 
    * Set the route for this shuttle. 
    * @param route The circular list of destinations. 
    */ 
    private void setRoute(ArrayList<String> route) 
    { 
     if(route.size() < 2) { 
      throw new IllegalStateException("setRoute must have at least two destinations"); 
     } 
     // Make a copy of the list parameter. 
     this.route = new ArrayList<String>(); 
     this.route.addAll(route); 
     destinationNumber = 0; 
     location = route.get(destinationNumber); 
     setNextDestination(); 
    } 

} 
+1

'Vehicle' не имеет конструктора' public Vehicle (String id) '. Кроме того, что вы ожидаете, передав 'Vehicle' свою собственную переменную' ident', которая никогда не была инициализирована? – Berger

+0

не могли бы вы отправить пример, пожалуйста, я понимаю, но потерян. –

ответ

0

Vehicle не имеет public Vehicle(String id) конструктор, только public Vehicle(String id, String base) конструктор.

Конструктор Taxi должен вызывать правильный (существующий) супер-конструктор.

Обратите внимание, что мы передадим локальную переменную id в супер-конструктор, перейдя к Vehicle. Его собственная пустая переменная ident не имеет смысла.

public Taxi(String id, String base) 
{ 
    super(id, base); 
    free = true; 
} 

Конструктор Shuttle пропускает id параметра (из документации), давайте добавим его и использовать первую запись из списка в качестве параметра base (опять-таки из документации):

 /** 
    * Constructor for objects of class Shuttle 
    * @param id This shuttle's unique id. 
    * @param route The route taken by this shuttle. 
    *    The first entry is the starting location. 
    */ 
    public Shuttle(String id, ArrayList<String> route) 
    { 
     super(id,route.get(0)); 
     setRoute(route); 
    } 
+0

Спасибо, что очень ценю: D –

 Смежные вопросы

  • Нет связанных вопросов^_^