[英]Accessing Instance Variable on Another Method Java
I'm trying to print the obj.age, obj.name and obj.gender on my printStuff method but I can't seem to access it.我正在尝试在我的 printStuff 方法上打印 obj.age、obj.name 和 obj.gender,但我似乎无法访问它。 What's the right way to access it?访问它的正确方法是什么?
Here's my code:这是我的代码:
public class myLove {
int age;
String name;
char gender = 'M';
static char status;
static String address;
public static void main(String args[]){
myLove.address = "Tiptop ambuclao";
myLove.status = 'S';
myLove obj = new myLove();
obj.age = 17;
obj.name = "John Doe";
obj.gender = 'M';
}
public void printStuff(){
System.out.println("Name: "+name);
}
} }
If you just want to call printStuff
from the main
method you can simply do this:如果您只想从main
方法调用printStuff
,您可以简单地执行以下操作:
public static void main(String[] args) {
MyLove myLove = new MyLove();
// set some data here
myLove.printStuff();
}
Since your printStuff
method is public, you can access it from any other class:由于您的printStuff
方法是公开的,您可以从任何其他 class 访问它:
public class OtherClass {
public static void printMyLove(MyLove myLove) {
myLove.printStuff();
}
}
This can be simply called from your main method like this:这可以简单地从您的 main 方法中调用,如下所示:
public static void main(String[] args) {
MyLove myLove = new MyLove();
// set some data here
OtherClass.printMyLove(myLove);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.