有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java像构造函数一样声明一个方法

我是Java新手,我一直在问自己是否可以像构造函数一样声明一个方法(没有返回类型,也没有void),或者这就是为什么它们被称为构造函数


共 (2) 个答案

  1. # 1 楼答案

    Java有严格的语法,也适用于Method DeclarationsConstructor Declarations

    方法的语法总是需要返回类型或void。 构造函数只有在与类同名时才有效

    以你为例:

    class Dog {
        public Dog() { // constructor for the class Dog
        }
    
        public void Dog() { // method with the name Dog
        }
    
        public void method() { // method with the name method
        }
    
        // invalid code
        // causes an error because the return type for the method is missing
        // and isn't a constructor because it hasn't the same name as the class.
        public method() {
        }
    }
    
  2. # 2 楼答案

    构造函数的存在是为了构建对象,而不是方法

    方法需要返回类型,因为它们从现有对象返回某些内容(即使返回类型为void),但构造函数用于构建对象,因此它不需要任何返回类型,因为调用对象时对象不存在