简体   繁体   中英

Accessing instance variables from another class from a static method

I have the following code:

    public static boolean isRelated(Animal first, Animal second){
    boolean result=false;
    if(first(parentA).equals(second(parentA)))
        result=true;

    return result;
}

basically, I need to be able to access the parent A instance variable that is in the Animal class from this static method.

I understand that, to access instance variables in a static method, you need to create an object but I already have 2 brought in.(Parent A and Parent B)

Could you guys tell me what the problem here is?

 if(first(parentA).equals(second(parentA)))

basically, I need to be able to access the parent A instance variable that is in the Animal class from this static method.

That is not the correct syntax to access instance members

should be

 if(first.parentA.equals(second.parentA))

More over use setters and getters to access the data such that

public class Animal  {
    private String parentA;

 //  code

  public String getParentA() {
    return parentA;
  }

  public void setParentA(String parentA) {
    this.parentA = parentA;
  } 
}

} 

Then use the line if(first.getParentA().equals(second.getParentA()))

In order to access instance variable, you need to use an instance. You don't have to create it each time you need it, as long as you have one.

And for your code:

if(first.getParentA().equals(second.getParentA()))

In this case you need to make sure than first.getParentA() isn't null before comparing (or else you'll get NPE)

Static methods are created in method area, and is the first to be created. Instance variables are created in heap after static methods are created. Hence, accessing instance variables directly is not possible. Always make use of an object to access such variables.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM