DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

+ Reply to Thread
Results 1 to 2 of 2
  1. #1
    Join Date
    Oct 2004
    Posts
    34

    returning an object

    Given the code below which adds weight to an object
    How can I create a method, NewTruckWeight() that will not change the state of the obj.
    Instead I want it to add pounds using the state of the current obj, instantiating and returning a new truck obj, without altering the state of the current obj?

    class TruckTest {
    public static void main(String[] args){
    Truck t1 = new Truck(5,125000);
    Truck t2 = new Truck(6,17000);

    //print the orginal weight of t1
    System.out.println(t1.getWeight());

    //call mutateWeight()
    t1.mutateWeight(1000);
    System.out.println(t1.getWeight());
    System.out.println(t2.getWeight());

    //here is the call NewTruckWeight(1000), I want to assign a new Truck reference to t2???

    }
    }

    class Truck {
    private int numaxles;
    private int weight;

    Truck(){
    };
    Truck(int axles, int w) {
    numaxles = axles;
    weight =w;
    }
    int getWeight() {
    return weight;
    }
    int getnumaxles() {
    return numaxles;
    }

    //add the mutateWeight()
    int mutateWeight(int i) {
    weight=(i + weight);
    return weight;
    }

    //add NewTruckWeight()???{

    }

    }
    Thanks, hope that is clear....

  2. #2
    Join Date
    Oct 2004
    Posts
    311
    In excense, what you need is to clone the old object...
    Their is an interface for this: Clone.

    If you look into this interface, it should set you on the right track.

Bookmarks

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


Top DevX Stories

Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL


Sponsored Links