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

Recommended Answers

All 4 Replies

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();
    }
}

This is very helpful! Thanks.

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.

commented: Too right +10

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.