Since it is a non-static variable, I'm trying to understand how we should call this class variable in both static & non-static method.
Code:
public class Person {
String firstName;
public static void main(String[] args) {
Person pps = new Person();
pps.setFirstName("Surendra");
System.out.println(getFirstName());
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public static String getFirstName() {
Person pps = new Person();
return pps.firstName;
}
}
Non-static data members cannot be accessed from static methods without an instance being provided in some way (e.g. as an argument, or created locally). Static methods are not naturally attached to any instance of the class, so there is no this
within the method.
To access the datamember from a specific instance, you need a non-static method called on the specific instance.
public String getFirstName() {
return this.firstName;
}
public static void main(String[] args) {
Person pps = new Person();
pps.setFirstName("Surendra");
System.out.println(pps.getFirstName());
}
If you'd like the same firstname to be shared between all instance of the class, then everything should be static:
public class Person {
static String firstName;
public static void main(String[] args) {
Person.setFirstName("Surendra");
System.out.println(Person.getFirstName());
}
public static void setFirstName(String newFirstName) {
firstName = newFirstName;
}
public static String getFirstName() {
return firstName;
}
}