java - 对java构造函数感到困惑

标签 java constructor

所以我正在学习 Java。我负责构造函数,并处理。我在理解它们的作用/用途时遇到了一些问题?我相信它们的使用类似于函数调用,在调用时将参数传递给函数

我的想法是否正确?

例如:

class test{
    void durp(String input){
        System.out.print(input);
    }
}

如果我要在我的主类中创建一个这样的对象:

test object = new test("嘿");

它会将 hey 作为字符串传递给 durp()

这是正确的吗?

最佳答案

If I was to make an object in my main class like this: test object = new test("hey"); it would pass "hey" as a string to durp() right?

不,因为您的方法 durp() 不是构造函数。它只是属于该类的一个方法,可以从创建的 Activity 对象中调用。

public class Test {
    /** this is a constructor */
    public Test() {
    } 

    /** this is also a constructor with a parameter */
    public Test(String arg1) { 
        System.out.println(arg1); 
    } 

    /** this is a method of Test */
    public void derp() {
    }
}

您可以阅读 this tutorial from oracle about constructors

关于java - 对java构造函数感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19066618/

相关文章:

c# - 私有(private)构造函数和公有参数构造函数

c++ - C++ 中自定义类的 HashMap 中的默认值

c++ - 在 C++ 中将类构造函数分配给带有参数的新构造函数

java - 如何在 Windows 上开发 Apple Java Extensions?

在类体之外定义函数时的 C++ 派生构造函数 - "no default constructor"

java - 类的构造函数不创建类

java - VB6现状/原生编译最佳桌面应用语言

java - 无效的 AES key 长度错误

java - 设计二维世界的最佳解决方案 - 生命游戏

java - 具有多个 JsonSerializer 映射的 DefaultKafkaProducerFactory