Results 1 to 4 of 4
- 03-19-2009, 06:22 PM #1
Member
- Join Date
- Mar 2009
- Posts
- 2
- Rep Power
- 0
Return an object to use in another method
Hi i was just wondering if it was possible to return an object to use in another method. ill explain what i mean using exarmple code:
method1{
...
Qestion qestion = new Qestion(...);
for(...){
method2();
qestion.addAnswer(answer);
}
method2{
...
Answer answer = new Answer(...);
return answer;
}
the "..." are put there to get rid of unesscerary code.
Basically i use method1 to input a qestion and create an object "qestion" of class Qestion.
Then method2 is used get input of an answer and create an object "answer" of class Answer.#
I then want to pass it back to method1 for use with the method "addAnswer" from the qestion class.
Unfortunatly this apparently doesnt work :S
Any suggestions??
Thanks
Chris
- 03-19-2009, 06:29 PM #2
Senior Member
- Join Date
- Sep 2008
- Posts
- 564
- Rep Power
- 5
you need to save the returned value into a local variable to the method you are using it in like so:
or you can use the method AS the variable as so:Java Code:method1{ ... Qestion qestion = new Qestion(...); for(...){ [B]Answer answer = [/B]method2(); qestion.addAnswer(answer); } method2{ ... Answer answer = new Answer(...); return answer; }
Java Code:method1{ ... Qestion qestion = new Qestion(...); for(...){ qestion.addAnswer([b]method2()[/b]); } method2{ ... Answer answer = new Answer(...); return answer; }
- 03-19-2009, 06:37 PM #3
Member
- Join Date
- Mar 2009
- Posts
- 2
- Rep Power
- 0
Thanks dude, i treid that and it has come up saying incompatible types :(
Do you have any surggestions as to what type to declare method2() as?
Currently it is declared like this:
private Object method2(){
...
}
and the addAnswer method is declared:
public void addAnswer(Answer answer)
{
answerList.add(answer);
}
where answerList is an arrayList in the Qestion class.
- 03-19-2009, 08:00 PM #4
Senior Member
- Join Date
- Sep 2008
- Posts
- 564
- Rep Power
- 5
have your arraylist use generics. if you aren't allowed, your only other option is casting: Using and Programming Generics in J2SE 5.0
Similar Threads
-
How I can return an object?
By CFW in forum New To JavaReplies: 4Last Post: 01-14-2009, 10:54 AM -
method that return 2 arguments
By itaipee in forum New To JavaReplies: 19Last Post: 01-12-2009, 05:36 PM -
return a null method
By valoyivd in forum New To JavaReplies: 2Last Post: 04-21-2008, 11:19 PM -
Return value of method
By cachi in forum New To JavaReplies: 1Last Post: 08-01-2007, 08:23 AM -
how to return an object from an arraylist
By elizabeth in forum New To JavaReplies: 1Last Post: 07-30-2007, 06:57 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks