我有以下课程:
public class Example {
private String name;
private int year;
public Example() {
name = "Clifford the big red dog";
year = 2020;
}
public void showData() {
// ?????
}
}
想象一下在主类中,我创建了上一个类(Example
)的对象并执行它的构造函数。然后,我想执行showData()
,并希望看到以下输出(给出此示例):
String name Clifford the big red dog
int year 2020
主要外观如下:
public static void main () {
Example example = new Example();
example.showData();
}
有什么办法可以做到这一点?
执行以下操作:
class Example {
private String name;
private int year;
public Example() {
name = "Clifford the big red dog";
year = 2020;
}
public void showData() {
System.out.println(name.getClass().getSimpleName() + " name " + name);
System.out.println(((Object) year).getClass().getSimpleName() + " year " + year);
}
}
public class Main {
public static void main(String[] args) {
Example example = new Example();
example.showData();
}
}
输出:
String name Clifford the big red dog
Integer year 2020
但是,由于showData
是class Example
的一种方法,它已经知道其实例变量,因此您可以简单地通过以下方式进行操作:
class Example {
private String name;
private int year;
public Example() {
name = "Clifford the big red dog";
year = 2020;
}
public void showData() {
System.out.println("String name " + name);
System.out.println("int year " + year);
}
}
public class Main {
public static void main(String[] args) {
Example example = new Example();
example.showData();
}
}
输出:
String name Clifford the big red dog
int year 2020