#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)
<@&987246399047479336> please have a look, thanks.
While you are waiting for getting help, here are some tips to improve your experience:
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();.
The main method is static. So you can call any static method that's also in the same class.
you can do
public static void main(String[] args){
printText("Hello, world!");
}
static void printText(String string){
System.out.println(string);
}
watch your names
printText vs print
ah yeah