嗨。我试图通过子类从超类调用方法,但不断得到错误。我试图调用的方法是setDestination()
,但编译器不断给我错误“找不到符号-方法setDestination(java.lang.string)“我的讲师说这是一个简单的方法调用和方法的参数不匹配但我有两个方法参数的类型String
,所以我有点困惑。
我的代码是:
超级车辆:
public class Vehicle
{
// A unique ID for this vehicle
private String id;
// The next destination of this Vehicle.
private String destination;
/**
* Constructor for objects of class Vehicle
*/
public Vehicle(String id)
{
destination = null;
}
/**
* Return the ID of the Vehicle.
* @return The ID of the Vehicle.
*/
public String getID()
{
return id;
}
/**
* Return the destination of the Vehicle.
* @return The destination of the Vehicle.
*/
public String getDestination()
{
return destination;
}
/**
* Set the intented destination of the Vehicle.
* @param destination The intended destination.
*/
private void setDestination(String destination)
{
this.destination = destination;
}
}
子类Taxi
:
public class Taxi extends Vehicle
{
// The location of this taxi.
private String location;
// 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 base, String id)
{
super(id);
location = base;
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 getID() + " at " + location + " headed for " +
destination;
}
/**
* Return the location of the taxi.
* @return The location of the taxi.
*/
public String getLocation()
{
return location;
}
/**
* Indicate that this taxi has arrived at its destination.
* As a result, it will be free.
*/
public void arrived()
{
location = destination;
destination = null;
free = true;
}
}
任何帮助都很感激。
5条答案
按热度按时间xtupzzrd1#
这是一个
private
方法。您不能访问私有方法。请将其更改为protected。只能在类中使用访问私有成员。
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
osh3o9ms2#
您已将
setDestination
定义为private
所以你不能通过继承来访问它。要么将它改为
protected
或`public。了解有关访问修饰符here.的更多信息ybzsozfc3#
private修饰符不能从类外部访问。
k2arahey4#
私有方法不是继承的,超类引用调用它自己的私有方法。
使用
private void setDestination(String destination)
代替rslzwgfq5#
除了前面的答案,
destination
类成员被声明为private
。因此,如果直接调用它,它将无法被任何子类访问(如Taxi类的arrived()和getStatus()方法)。要么将
destination
声明为protected,要么将getDestination()的修饰符更改为public或protected,并使用该方法而不是直接访问类成员-如前面提到的其他方法。