In the following class I have the method getName()
which I wanted it to be static
because I was going to use it inside another method in the same class Person
(I wanted to do this: Person.getName()
), however when I put it I static
got the following error:
non-static variable name cannot be referenced from a static context
, a possible solution would be to remove the private
to variable name
,
is there any other solution for this problem?
Could private
the variable be preserved name
?
class Person{
private String name, gender;
Person(String name, String gender){
this.name=name;
this.gender=gender;
}
static String getName(){//si se le pone static marca error.
return name;
}
String getGender(){
return gender;
}
}
Static methods can only access static data.
The data
name
,gender
are variables of an instance of the class Person , you can't know them unless you do anew Person("Pedro","H");
Imagine in "real life"... you know what a Person is , what would you do if I asked you "Give me the name of the person"... would you ask me which person?
oh! but there is a person named Michelle and there is another person named Octavio, those are instances of People.
brief explanation
Non-static members belong to instances/objects of a class. Static members belong to the class. If a getter is declared static, it is general for all instances of the class and not for the specific value for each instance. Since this is inconsistent, the solution to your problem is to not use static getters for your attributes.
long explanation
In a class, when you declare a member (attribute or method) as static, it means that the member belongs to the class and not to an instance . This means that these members can be accessed without creating an instance of a class.
Example:
Departure
Since the static member belongs to the class, it cannot access the instance members, since the instance members belong to a particular instance (object) of the class. Example:
Departure:
As you can see, static members can be considered global to all instances of a class, while non-static elements correspond to each instance of a class. Here's an example showing the differences: