Java:Getter、Setter 和构造函数

标签 java class constructor setter getter

我正在尝试创建一个保存位置的类,包括以下方法:

每个数据字段的 setter (修改器) 对于位置名称,您应该使用trim() 方法删除任何前导或尾随空格。

每个数据字段的 getter (访问器)

构造函数:您应该只有一个获取地名、纬度和经度的构造函数。尽管可能需要修剪字符串,但您可能期望数据有效。

public class Location {
    public Location(String aCity, double aLatitude, double aLongitude)
    {
        String city = aCity;
        double latitude = aLatitude;
        double longitude = aLongitude;
    }
    void setLocation(String theCity)
    {
        city = theCity.trim();
    }
    void setLatitude(double lat)
    {
        latitude = lat;
    }
    void setLongitude(double long1)
    {
        longitude = long1;
    }
    public String getLocation()
    {
        return city;
    }
    public double getLatitude()
    {
        return latitude;
    }
    public double getLongitude()
    {
    return longitude;
    }
}

我不确定我哪里出了问题,两个城市、两个纬度和两个经度都出现错误。这是我第一次写类(class),所以请帮我简化所有内容。感谢您抽出时间。

最佳答案

你就快到了。你有:

public Location(String aCity, double aLatitude, double aLongitude)
{
    String city = aCity;
    double latitude = aLatitude;
    double longitude = aLongitude;
}

您正在构造函数中声明局部变量。您实际上想要声明字段:

public class Location {

    private String city;
    private double latitude;
    private double longitude;

    public Location(String aCity, double aLatitude, double aLongitude)
    {
        city = aCity;
        latitude = aLatitude;
        longitude = aLongitude;
    }

    ...

}

查看 declaring member variables 上的官方教程。它简洁且写得很好,可以让您更好地了解正在发生的事情。

关于Java:Getter、Setter 和构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22419349/

相关文章:

java - 使用 corejava 程序进行无密码的 MySQL 连接(用户 'root' @'localhost' 的访问被拒绝)

java - Maven 构建失败,因为它无法识别添加到构建路径的 .jar

python - python中的父/子类结构

java - 分配给在没有实例化对象的方法中声明的类变量

java - 文件下载OutputStream的内存使用情况

Java 数据绑定(bind)最佳实践

php类构造函数

c++ - 奇怪的 "type class::method() : stuff "语法 C++

constructor - 构造函数如何使用复杂的算法初始化最终字段?

python - 从字符串创建 Python 对象