gpt4 book ai didi

java - 从父类(super class)调用方法

转载 作者:搜寻专家 更新时间:2023-11-01 04:06:02 25 4
gpt4 key购买 nike

嗨。我试图通过子类从父类(super class)调用方法,但一直出错。我试图调用的方法是 setDestination() 但是编译器一直给我错误“找不到符号 - 方法 setDestination(java.lang.string)”我的讲师说这是一个简单的错误方法调用的参数和方法的参数匹配,但是我有 String 类型的两个方法参数,所以我有点困惑。

我的代码是:

super 车辆:

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

子类出租车:

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

非常感谢任何帮助。

最佳答案

这是一个私有(private)方法。您不能访问私有(private)方法。将其更改为 protected 。

您只能在类中访问私有(private)成员。

   Modifier Class   Package Subclass    World
---------------------------------------------
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

关于java - 从父类(super class)调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20814209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com