writing a method with object parameters


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 3 of 3

Thread: writing a method with object parameters

  1. #1
    Join Date
    Nov 2004
    Posts
    19

    writing a method with object parameters

    im writing a class that performa arithmetic on weights, im trying to write a method that adds two weight objects together (in my case the weights are in pounds and ounces so the method itself will add the pounds and ounces individually but i want to parse 2 weight objects to the method

    what wil the mthod delcartion be to write such a method?

    public ? addWeights(Weights w1, Weights w2){
    //implementation
    }

    //called from a test program
    Weights w1 = new Weights(13, 12)
    Weights w2 new Weights(10, 3)
    addWeights(w1, w2)

    pelase help

  2. #2
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    public void addWeights(Weights w1, Weights w2){
    //implementation
    }

    As it is not supposed return anything (?). If there is a probalility for invalid Weight objects that you want to trap you can either return a boolean indicating failure or success;

    public boolean addWeights(Weights w1, Weights w2){
    //implementation
    }

    or declar the addWeights method to throw an Exception when the Weight object(s) are up the creek.

    public void addWeights(Weights w1, Weights w2) throws Exception {
    //implementation
    .
    .
    if (somethingVeryWrong) {
    throw new Exception("These Weights are insane");
    }


    }
    eschew obfuscation

  3. #3
    Join Date
    Feb 2004
    Posts
    541
    The place where the question mark is located is for the return type of the method. This is where you say what will happen when the method exits. If the method ends by producing a value or object you say what type of value or object. If nothing is returned you say void.

    I imagine that the addWeights method will produce a new Weights object containing the result. This means you need to put Weights where the question mark is.

    Code:
    public Weights addWeights(Weights w1, Weights w2)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center