简体   繁体   English

无法获取构造函数方法以使用Java打印到控制台

[英]Cannot get constructor method to print to the console in Java

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: 我在尝试从main方法中实例化对象时尝试获取构造函数方法以打印到控制台时遇到问题:

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 : 去除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 void Message() { }应该是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: 这不是构造函数,而是普通方法,您必须删除void才能成为构造函数:

public Message() {...} 公共Message(){...}

NOT

public void Message(){...} 公共无效 Message(){...}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM