#if i have a method defined in a class outside of main, can i use it in the main class?

1 messages ยท Page 1 of 1 (latest)

sick sleet
#

new to java

stray briarBOT
#

<@&987246399047479336> please have a look, thanks.

stray briarBOT
#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.

Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.

#

Here is an AI assisted attempt to answer your question ๐Ÿค–. Maybe it helps! In any case, a human is on the way ๐Ÿ‘. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.

#

Yes, you can use a method defined in a class outside of the main method. In Java, methods can be defined in any class and can be accessed from other classes as long as they are visible (i.e., have appropriate access modifiers).

To use a method from another class in the main method, you need to create an instance of that class and then call the method on that instance. Here's an example:

public class MyClass {
    public void myMethod() {
        System.out.println("Hello from myMethod!");
    }
}

public class MainClass {
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        obj.myMethod(); // calling myMethod from the instance of MyClass
    }
}

In this example, myMethod() is defined in the MyClass outside of the main method. To use it in the MainClass, we create an instance of MyClass using MyClass obj = new MyClass(); and then call the method using obj.myMethod();.

fiery talon
#

yes

#

for example

royal shell
fiery talon
# fiery talon for example

you can do

public static void main(String[] args){
    printText("Hello, world!");
}
static void printText(String string){
    System.out.println(string);
}
royal shell
#

printText vs print

fiery talon
#

ah yeah