Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从不同类的对象访问单个变量?_Java_Class_Oop_Methods - Fatal编程技术网

Java 从不同类的对象访问单个变量?

Java 从不同类的对象访问单个变量?,java,class,oop,methods,Java,Class,Oop,Methods,我有三节课;人员、人员、主程序和日期。date类包含日、月和年的3个变量。我正在尝试在Person类中创建一个方法,该方法以firstname lastname middle initial day month year的格式返回字符串。因为firstname、lastname和中间的首字母是Person类的一部分 return String.format("%s %s %s %s %s %s" this.firstname, this.lastname, this.middleinitial

我有三节课;人员、人员、主程序和日期。date类包含日、月和年的3个变量。我正在尝试在Person类中创建一个方法,该方法以firstname lastname middle initial day month year的格式返回字符串。因为firstname、lastname和中间的首字母是Person类的一部分

 return String.format("%s %s %s %s %s %s" this.firstname, this.lastname, this.middleinitial ... )

在this.middleinitial之后,是否有一种语法可以用于调用Date类中的day、month和year的各个变量?我只是找不到符号与我已经尝试到目前为止。我是否需要将另一个方法设置为我的Date类,以这种方式格式化日期,并亲自从我的方法调用该方法?

尝试将Date类中的变量设置为公共的,或者为它们创建getter


有关getter和setter的信息,请参阅。

我不知道是否理解您的要求,但请尝试以下方法:

在你的个人课上:

Person(Date date) {
   this.date = date;
}

.
.

return String.format("%s %s %s %s" this.firstname, this.lastname, this.middleinitial, this.date.getFormatDate() )
在你的约会课上:

Date {

.
.

public void getFormatDate() {
   return this.day + "/" + this.month + "/" + this.year;
}

}
最好使用Calendar和SimpleDataFormat来格式化日期,而不是使用带有这些变量的date类,但是对于当前的情况,我认为这是可以的


我希望这有帮助,abs

如果日期与某人有关,例如生日或雇佣日期,则每个实例上都应该有另一个成员变量,就像firstName和lastName一样

无需创建自己的日期类。使用,Java 8及更高版本中内置的类仅表示一个日期,没有一天中的时间,也没有时区

LocalDate ld = LocalDate.of( 2017 , Month.JANUARY , 23 );
然后使用DateTimeFormatter类生成表示其值的字符串。该类甚至可以自动本地化

DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( Locale.CANADA_FRENCH );
String dateOutput = ld.format( f );
如果需要,您确实可以提取LocalDate的每一部分

对于构建如此长的文本,我不会使用String.format。使用+运算符或StringBuilder/StringBuffer类连接

StringBuilder s = new StringBuilder();
s.append( fName ).append( " " ).append( dateOutput ) ;
…

对不起,但是什么??请张贴所有的代码,给出错误和确切的错误信息。这工作谢谢你。我以前没有给我的同事打电话。
StringBuilder s = new StringBuilder();
s.append( fName ).append( " " ).append( dateOutput ) ;
…
Date date = new Date( ... );
return String.format("%s %s %s %s %s %s" this.firstname, this.lastname, this.middleinitial, date.getYear(), date.getMonth(), date.getDay() );