我编写了 Accessors 和 Mutators 方法,但仍然无法访问私有变量!为什么?
我用其私有变量编写了我的类,然后编写了访问这些变量所需的访问器和修改器方法,但是当我在编写主类后运行它时,这不起作用。为什么会发生这种情况?在这里检查我的代码:
public class DateTest{
public static void main (String [] args){
Date d1 = new Date();
Date d2 = new Date();
d1.month = "February ";
d1.day = 13;
d1.year = 1991;
d2.month = "July";
d2.day = 26;
d2.year = 1990;
d1.WriteOutput();
d2.WriteOutput();
}
}
class Date {
private String month;
private int day;
private int year;
public String getMonth(){
return month;
}
public int getDay(){
return day;
}
public int getYear(){
return year; }
public void setMonth(String m){
if (month.length()>0)
month = m;
}
public void setDay(int d){
if (day>0)
day = d; }
public void setYear(int y){
if (year>0)
year = y;
}
public void WriteOutput(){
System.out.println("Month " + month + "Day "+ day + " year" + year);
}
}
请大家耐心等待我,我真的是一个“新手”程序员
I wrote my class with its private variables and then I wrote the accessor and mutator methods needed to access those variables, but that does not work when I run it after writing the main class. Why does that happening ?check my code here :
public class DateTest{
public static void main (String [] args){
Date d1 = new Date();
Date d2 = new Date();
d1.month = "February ";
d1.day = 13;
d1.year = 1991;
d2.month = "July";
d2.day = 26;
d2.year = 1990;
d1.WriteOutput();
d2.WriteOutput();
}
}
class Date {
private String month;
private int day;
private int year;
public String getMonth(){
return month;
}
public int getDay(){
return day;
}
public int getYear(){
return year; }
public void setMonth(String m){
if (month.length()>0)
month = m;
}
public void setDay(int d){
if (day>0)
day = d; }
public void setYear(int y){
if (year>0)
year = y;
}
public void WriteOutput(){
System.out.println("Month " + month + "Day "+ day + " year" + year);
}
}
Please guys just be patient with me, I'm really a "novice" programmer
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
应该调用访问器方法。就是这样。
The accessor methods are supposed to be called. That's it.
Java 没有像 C# 那样的语法糖,并且不允许您从
object.property
进行调用,即使您已经提供了访问方法。属性纯粹是一种设计模式,并不反映在语言本身的语法中。您需要显式调用它们,例如
d1.setMonth("February ");
和String val = d1.getMonth();
。Java has no syntactic sugars like C# and won't allow you to do calls in from
object.property
even though you have provided the access methods. Properties are purely a design pattern and are not refleted in syntax of a language itself.You need to call them explicitly like
d1.setMonth("February ");
andString val = d1.getMonth();
.始终使用 setter 和 getter 来访问私有变量。
Always use setters and getters to access the private variables.
私有成员只能在同一个类的成员内部直接访问。
DateTest
是另一个类,因此下面的代码是不可能的将上面的代码替换为使用相应的 setter 方法。
private members can be directly accessed only within the members of the same class.
DateTest
is another class and hence the below is not possibleReplace the above code with using corresponding setter methods.