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. 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:
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:
public class OtherClass {
public static void printMyLove(MyLove myLove) {
myLove.printStuff();
}
}
This can be simply called from your main method like this:
public static void main(String[] args) {
MyLove myLove = new MyLove();
// set some data here
OtherClass.printMyLove(myLove);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.