I am having an issue in terms of trying to get the constructor method to print to the console when the object has been instantiated from within the main
method:
public class HelloWorld {
public static void main(String[] args) {
Message message = new Message();
System.out.println(message.helloWorld());
}
}
Here is the object that has been instantiated:
public class Message {
public void Message() {
// constructor method
System.out.println("Constructor Method!");
}
public String helloWorld() {
return "Hello, World!";
}
}
I assumed the constructor method would print to the console?
This does not declare a constructor:
public void Message() {
Constructors have no return type; this is a method. Remove void
:
public Message() {
problem:
public void Message() {
It is not a constructor, it is a method thus it is not called upon creating the instance of your class
it should be this:
public Message()
Why are you thinking that constructor method should print? It will not print. Because you have not declare a constructor. You just only have 2 methods.
This is not a constructor. this is just another method. Constructors doesn't have a return type.
public void Message() {
// constructor method
System.out.println("Constructor Method!");
}
But if you have like this
public Message() {
// constructor method
System.out.println("Constructor Method!");
}
Then it is a constructor and it will get print
Wrong constructor declaration , public void Message() { }
should be public Message() { }
:
public class Message {
public Message() { // <-- Here's the correct constructor declaration
System.out.println("Constructor Method!");
}
public String helloWorld() {
return "Hello, World!";
}
}
this is not a Constructor but a normal method, you have to remove the void to be a constructor:
public Message() {...}
NOT
public void Message(){...}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.