Search code examples
javaclassmethodscallextends

Call a method of another class that has another class extended


How to call a method of another class that has another class extended?

I have two classes:

public class Main extends JavaPlugin {
    public void whatever() {
        // whatever
    }
}

public void AnotherClass implements Listener {
    // whatever
}

When I try to call a method of Main in AnotherClass:

public class AnotherClass implements Listener {
    Main main = new Main();

    main.whatever();
}

It is not working but when I call a method of a function that does not extends something it works fine.


Solution

  • There are a few issues I see.

    public void AnotherClass implements Listener
    

    You can't have a void class.

    You can't have two public classes in one file.

    Your class declaration should look like this

    class AnotherClass implements Listener
    

    You are also calling main.whatever() from outside any method, which as far as I know will not work, unless it's in a static block. You need call methods from within other methods.

    class AnotherClass implements Listener {
    
        public void something() {
            Main main = new Main();
            main.whatever();
        }
    }