943,837 Members | Top Members by Rank

Ad:
  • Java Discussion Thread
  • Unsolved
  • Views: 10696
  • Java RSS
Jun 16th, 2007
0

how to call a method defined in another file?

Expand Post »
codes in two files. Is there a way to use a method cross files?
Reputation Points: 10
Solved Threads: 0
Newbie Poster
dajiebuda is offline Offline
8 posts
since Jun 2007
Jun 16th, 2007
0

Re: how to call a method defined in another file?

The class calling the method needs a reference to the other class. For example, ClassA instantiates ClassB (Below) and ClassB needs to call a method provided by ClassA. The 'this' keyword can be passed into ClassB's constructor to provide it with a reference to ClassA.

E.g.

Java Syntax (Toggle Plain Text)
  1.  
  2. public class ClassA{
  3. ClassB subordinate;
  4.  
  5. public static void main(String[] args){
  6. subordinate = new ClassB(this);
  7. }
  8.  
  9. public void mymethod(){
  10. //do something
  11. }
  12. }
  13. public class ClassB{
  14. ClassA master;
  15.  
  16. public ClassB(ClassA master){
  17. this.master = master;
  18. master.mymethod();
  19. }
  20. }
Last edited by Cerberus; Jun 16th, 2007 at 4:00 pm.
Reputation Points: 27
Solved Threads: 14
Junior Poster
Cerberus is offline Offline
162 posts
since Sep 2006
Jun 16th, 2007
0

Re: how to call a method defined in another file?

This is very helpful! Thanks.
Reputation Points: 10
Solved Threads: 0
Newbie Poster
dajiebuda is offline Offline
8 posts
since Jun 2007
Jun 17th, 2007
1

Re: how to call a method defined in another file?

but don't go that way. Learn about proper Object Oriented design rather than trying to use Java as if it were a procedural language.
Team Colleague
Reputation Points: 1658
Solved Threads: 331
duckman
jwenting is offline Offline
7,719 posts
since Nov 2004
Jun 17th, 2007
0

Re: how to call a method defined in another file?

Click to Expand / Collapse  Quote originally posted by dajiebuda ...
codes in two files. Is there a way to use a method cross files?
what do you mean with use? you can call it by creating the instance of that method
Reputation Points: 21
Solved Threads: 7
Junior Poster in Training
ProgrammersTalk is offline Offline
83 posts
since Jun 2007

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Java Forum Timeline: Java Code for interesting Java Game
Next Thread in Java Forum Timeline: Beginner Help





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC