简体   繁体   English

我们可以在不创建对象的情况下调用构造函数吗

[英]Can we invoke a constructor without creating its object

What is happening in this code?这段代码发生了什么? I want to display the output as "Printing data ASD" without invoking the constructor.我想在不调用构造函数的情况下将输出显示为“打印数据 ASD”。

The child class:子类:

package com.javatraining;

public class test1 extends test2{

    public static void main(String[] args) {
        disp();
    }
}

The parent class:父类:

package com.javatraining;

public class test2
{
    public static String name;  

    public test2(){
        name="ASD";
    }

    public static void disp(){
        //test2 t=new test2();
        System.out.println("Printing data "+name);
    }
}

Assign a value to the name object of test 2 class.为 test 2 类的名称对象赋值。 It will work.它会起作用。

public static void main(String[] args) {
        test2.name = "ASD";
        disp();
    }

NO . You can't invoke a constructor without creating an object.您不能在不创建对象的情况下调用构造函数。
Unless you create object of test2 by test2 = new test2();除非您通过test2 = new test2();创建 test2 的对象test2 = new test2(); , you will get null in name. ,您将在名称中获得null

The only way you would have invoked a constructor if it was static, but constructors in Java can't be static.如果构造函数是静态的,您将调用它的唯一方法,但Java 中的构造函数不能是静态的。 So you have create an object to invoke constructor.所以你已经创建了一个对象来调用构造函数。

public class MainJava extends Test{

    public static void main(String[] args){
        //Option 1
        disp();

        //Option 2
        name = "ABCD";
        disp();

        //Option 3
        new Test();
        disp();
    }

    }

    class Test {
    public static String name = "TEMP";

    public Test() {
        // Will not get called. Unless you create Object
        name = "ASD";
    }

    public static void disp() {
        System.out.println("Printing Data " + name);
    }
}

You don't have to invoke the constructor of parent class at all, if all you want in your child class is an initialised value of name class member, then you can do the declaration + initializations in one go as below.您根本不必调用父类的构造函数,如果您在子类中想要的只是name类成员的初始化值,那么您可以一次性完成声明+初始化,如下所示。

public static String name = "ASD";

The above style makes it clear at a glance how the variable is initialised and it will also print the expected output.上面的样式一目了然地说明了变量是如何初始化的,并且还会打印预期的输出。

Of course, if the initialization value is different in different constructors, you must do it in the constructor.当然,如果在不同的构造函数中初始化值不同,则必须在构造函数中进行。 You can read more about object initialisation in this article .您可以在本文中阅读有关对象初始化的更多信息。

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

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