Issue
In Eclipse I've created a (Project > Package > Classes(HelloWorld.java, HelloUniverse.java )
How do I connect the second class to the main function,
package com.shindeaditya.first;
public class HelloWorld {
public static void main(String args [])
{
System.out.println("Hello World");
new HelloUniverse();
}
}
package com.shindeaditya.first;
public class HelloUniverse {
public void helloUniverse() {
System.out.println("Hello everyone I'm new to JAVA");
}
}
So that I get the output as
Hello World
Hello everyone I'm new to JAVA
Solution
There are two ways to solve this:
1: Change the function so it becomes the constructor, Remove the void and make the first letter a capital letter like the class name. Source: https://www.w3schools.com/java/java_constructors.asp
package com.shindeaditya.first;
public class HelloUniverse {
public HelloUniverse() {
System.out.println("Hello everyone I'm new to JAVA");
}
}
2: Call the function on the object, by saving it (for example) to an object and calling the function method. Source: https://www.w3schools.com/java/java_class_methods.asp
package com.shindeaditya.first;
public class HelloWorld {
public static void main(String args [])
{
System.out.println("Hello World");
// with a seperate variable
HelloUniverse universe = new HelloUniverse();
universe.helloUniverse();
// in one line
(new HelloUniverse()).helloUniverse();
}
}
Answered By - NLxDoDge
Answer Checked By - Mary Flores (JavaFixing Volunteer)