Jean
Jean

Reputation: 1490

How to access variable in a public method in Java?

public class Test(){
  public List makeList(){
    //some code
    ....
    double density = mass / vol;
    return mylist;
  }
}

How can I refer to density even though I only returned a list? In Python, I can call self.density

I know I can create another class Pair<List, Double> but I would rather not do that due to clutter.

Upvotes: 1

Views: 112

Answers (3)

Manuel
Manuel

Reputation: 4238

Make density an instance member of your Test class.

public class Test { // NO open/close parenthesis here!

  private double density;

  public List makeList() {
    //some code
    ....
    this.density = mass / vol;
    return mylist;
  }

  public double getDensity() {
    return this.density;
  }

}

Then call:

Test test = new Test();
List myList = test.makeList();
double density = test.getDensity();

Upvotes: 3

Mark Nenadov
Mark Nenadov

Reputation: 6967

You need to declare density as a member of the class Test outside the method and merely assign it within the method. If it is declared within the method, it can't be accessed elsewhere.

Like so:

public class Test{
     private double density;

     public List makeList(){
        //some code
        ....
        density = mass / vol;
        return mylist;
     }
}

Upvotes: 0

Andreas Fester
Andreas Fester

Reputation: 36649

In Python, I can call self.density

No, this is not the same. What yo have defined in your code is a local variable - its scope is limited to makeList().

If you want to refer to it from other methods, you can make it an instance variable (this is what you do with self in Python):

public class Test {
   private double density = 0.0;

   public List makeList(){
      //some code
      ....
      density = mass / vol;
      return mylist;
   }
}

Upvotes: 6

Related Questions