1
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.

3
  • 1
    "In Python I can call self.density". No you can't, not unless it's a member of the object Test. Commented Jul 22, 2013 at 10:01
  • 1
    The behaviour in Python and Java here are identical (assuming you're talking about a public field of the class) Commented Jul 22, 2013 at 10:01
  • 1
    Please see variable scope and life cycle for reference. Commented Jul 22, 2013 at 10:02

3 Answers 3

6

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;
   }
}
Sign up to request clarification or add additional context in comments.

3 Comments

You might want to fix public class Test() too (as Manuel pointed out).
@Jonik Thanks - been to focused on the scope related question :)
Thanks for the explanation, I only started learning Java recently.
3

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();

Comments

0

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;
     }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.