-3

I've created an object inside a method and inside main. I want the object inside of the method to be returned. I thought everything in Java was returned by reference not value, so I'm not quite sure how to do this.

public class Measurement
{
    private int value;
    private String units; 

    public static void main(String[] args)
    {
         Measurement a = new Measurement(2,"cm");
         Measurement b = new Measurement(5,"cm");
         Measurement c = new Measurement();

         c = a.mult(b); 
    }

    public Measurement mult(Measurement aObject)
    {
         Measurement c = new Measurement();

         c.value = this.value * aObject.value;
         c.unit = this.unit; 

         return c;
    }
}
White Lotus
  • 353
  • 2
  • 6
  • 16
  • Code looks like correct to me, also if you don't need `Measurement c = new Measurement()` since you are returning a new `Measurement` from the `mult` method, so the just created one is lost. – Jack Jan 25 '16 at 05:04
  • I'm wondering if it has to do with this line **c.unit = this.unit;** I don't see a _unit_ variable in this class or any method that assigns _unit_ a value – Ethan Fischer Jan 25 '16 at 05:10
  • 1
    What is your question exactly? What is the error message? – Sweeper Jan 25 '16 at 05:17
  • 1
    What are the types of value and units? You can paste the actual code... – OneCricketeer Jan 25 '16 at 05:23
  • 1
    Note, just for future reference: [Java is ***always*** pass-by-value. No exceptions.](http://stackoverflow.com/a/40523/1079354) – Makoto Jan 25 '16 at 05:31

1 Answers1

1

I think you don't understand how to declare class-level variables. You CANNOT declare variables like this:

private unit;
private value;

A class-level variable (or field) declaration takes the following form:

[modifiers] (variable type) (name);

Where the things in the the [] are optional. And I think your declaration lacks a variable type! You should add the word int and String:

private int value;
private String unit;

And that's it! Your other code looks pretty normal. I think the only error is the variable declarations.

Sweeper
  • 213,210
  • 22
  • 193
  • 313