Results 1 to 4 of 4
  1. #1
    dom12 is offline Member
    Join Date
    Nov 2010
    Posts
    7
    Rep Power
    0

    Question Returning an object

    I am working on a project that does different operations on fractions. I have created fraction objects called f1 and f2, with numerator and denominator as their parameters.

    My teacher has instructed us to make it work with this in the main method:

    Java Code:
    fraction f1 = new fraction(3,4);
    fraction f2 = new fraction(1,8);
    fraction result = f1.plus(f2);
    Now assuming that everything in the plus method works correctly, how would I return a fraction?

    In the fraction class I have:

    Java Code:
    public fraction plus(fraction f)
    but I don't know how to return an object.
    Would I just return the two parameters like:

    Java Code:
    return (numerator,denominator);
    ?

    Sorry if my terminology or explanation is poor, but I'm in my first semester of java.

  2. #2
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    If you have an object in the function, like this:
    Java Code:
    public fraction plus(fraction f) {
        this.value += f.value;
    }
    Then you can just return this.

    If you do something like this...
    Java Code:
    public fraction plus(fraction f) {
        fraction n = new fraction(this.value + f.value);
    }
    Then you'll want to return n instead.

    Personally I'd go with the first method, but it all depends what you have so far. I'm just using .value as a placeholder for whatever your data already is, since I can't see your actual source.

  3. #3
    dom12 is offline Member
    Join Date
    Nov 2010
    Posts
    7
    Rep Power
    0

    Default

    Thanks Zack! I used the second method and all is working now.

  4. #4
    makpandian's Avatar
    makpandian is offline Senior Member
    Join Date
    Dec 2008
    Location
    Chennai
    Posts
    444
    Rep Power
    6

    Default

    Try to understand how it works.
    Mak
    (Living @ Virtual World)

Similar Threads

  1. Replies: 1
    Last Post: 08-28-2010, 01:27 PM
  2. Method, returning reference to an object
    By Saletra in forum New To Java
    Replies: 3
    Last Post: 08-23-2010, 08:22 PM
  3. returning an object from a method
    By bigj in forum New To Java
    Replies: 7
    Last Post: 01-08-2010, 12:39 PM
  4. returning arrays
    By cjohnson412 in forum New To Java
    Replies: 4
    Last Post: 11-25-2008, 01:30 PM
  5. Why is my list returning nothing?
    By xcallmejudasx in forum New To Java
    Replies: 2
    Last Post: 11-05-2008, 03:51 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •