【发布时间】:2016-02-13 17:28:46
【问题描述】:
我刚刚开始接触 Java 中的面向对象编程。我很好奇下面两段代码之间的区别(如果有的话)。
public class BuyAHouseInc
{
// Instance variables
private String firstName;
private String surname;
private String address;
private int budget;
// method to set the first name in the object
public void setFirstName(String firstName)
{
this.firstName = firstName; // stores the first name
}
// method to retrieve the first name from the object
public String getFirstName()
{
return firstName; // return value of first name to caller
}
// method to set the surname in the object
public void setSurname(String surname)
{
this.surname = surname; // stores the surname
}
// method to retrieve the surname from the object
public String getSurname()
{
return surname; // return the value of surname to caller
}
// method to set the address in the object
public void setAddress(String address)
{
this.address = address; // stores the address
}
// method to retrieve the address from the object
public String getAddress()
{
return address; // return the value of address to caller
}
// method to set the budget in the object
public void setBudget(int budget)
{
this.budget = budget; // store the budget
}
// method to retrieve the budget from the object
public int getBudget()
{
return budget; // return the value of address to caller
}
}
这是第二段代码;
public class BuyAHouseInc
{
public void displayClient(String firstName, String surname, String address, int budget)
{
System.out.println("Client Name: " + firstName + " " + surname);
System.out.println("Address: " + address);
System.out.println("Budget: " + "€" + budget);
}
}
我更喜欢这里的第二段代码,因为它更易于理解,但我已经阅读了很多关于方法和对象的内容,但我无法弄清楚实际的区别是什么。 set 和 get 方法是输入值的安全方法吗?
【问题讨论】:
-
第二个代码与第一个代码无关...
-
您可能想了解encapsulation 以了解您为什么要使用第一个代码
-
这是一个关于 POJO 的好链接 en.wikipedia.org/wiki/Plain_Old_Java_Object ,您的 displayClient 方法看起来像一个 toString 方法 stackoverflow.com/questions/3615721/…
-
Set 和 get 方法使用封装,也就是私有变量只能从类中访问。我知道这一点,但是当两个代码都被编译时,它们对我的运行是一样的。
-
@eamonn-keogh 如果您看到相同的行为,则说明您正在运行此处未显示的代码。第一个代码块不打印任何内容到标准输出,但第二个 only 打印到标准输出。