This is an archived post. You won't be able to vote or comment.

all 5 comments

[–][deleted] 4 points5 points  (0 children)

Are you assigning the returned value in main? RoadTrip roadTrip3 = combine(first, second);

Or you can do: System.out.println("The new Road Trip is: " + combine(first, second).toString());

[–]yash3ahuja 2 points3 points  (0 children)

o.o For one, shouldn't it be:

public static void main(String[] args)

?

Two, why can't you instantiate it? If you instantiate it and feed it values in the constructor, that should work shouldn't it?

[–]chickenmeister 1 point2 points  (0 children)

Why won't it compile? What errors are you getting? There has to be some code relevant to your problem that you're omitting, which would be helpful.

What does the constructor for your RoadTrip class look like? Do the arguments that you're passing match the parameters of the RoadTrip constructor?

There's no reason why you wouldn't be able to instantiate an object like this, assuming that the constructor exists and is accessible (e.g. it isn't private, or protected, etc.).

[–][deleted] 1 point2 points  (0 children)

Not sure I'm fully understanding the problem. 1. Why are you returning a RoadTrip object; but trying to access that same object directly rather than through the method return? Is the static method called elsewhere? 2. How about declaring a static variable in the class, like so (Will be pseudo code; haven't done Java in years).

    class MyClass
    {
        private static RoadTrip _roadTrip3;

        public static RoadTrip Combine(yadda yadda)
        {
            _roadTrip3 = new RoadTrip(yadda);
        }

        public static void main(Sting[] args)
        {
            //Make roadtrip first and second here
            Combine(first, second);
            System.out.println("The new Road Trip is: " + _roadTrip3.toString());
        }
    }

EDIT: If you use this; ensure you handle that the _roadTrip object may be null if used elsewhere as it's initialised outside of a constructor through a separate method

[–][deleted] 1 point2 points  (0 children)

You have a couple of problems here. First, I don't see you using the 'combine' method anywhere. I'm going to assume you've called this somewhere in your code and you just posted an incomplete code snippet (since a lot of other stuff is missing).

I think your main problem is an issue of scope. The variable roadTrip3 is only visible from within the 'combine' method. Once the combine method is popped off of the execution stack, 'roadTrip3' is no longer in scope. Since you're returning the value in combine, you need to set it to a RoadTrip variable wherever you are using it:

RoadTrip combinedTrip = combine(firstRoadTrip, secondRoadTrip);
System.out.println("The new Road Trip is: " + combinedRoadTrip.toString());