954,536 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

how to call a method defined in another file?

codes in two files. Is there a way to use a method cross files?

dajiebuda
Newbie Poster
8 posts since Jun 2007
Reputation Points: 10
Solved Threads: 0
 

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.

public class ClassA{
    ClassB subordinate;
 
    public static void main(String[] args){
        subordinate = new ClassB(this);
    }
 
    public void mymethod(){
        //do something
    }
}
public class ClassB{
    ClassA master;
 
    public ClassB(ClassA master){
        this.master = master;
        master.mymethod();
    }
}
Cerberus
Junior Poster
162 posts since Sep 2006
Reputation Points: 27
Solved Threads: 14
 

This is very helpful! Thanks.

dajiebuda
Newbie Poster
8 posts since Jun 2007
Reputation Points: 10
Solved Threads: 0
 

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.

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 
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

ProgrammersTalk
Junior Poster in Training
84 posts since Jun 2007
Reputation Points: 21
Solved Threads: 7
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You