我们如何确认对象是在java中创建的

时间:2022-05-20 19:06:54

We all know that we can't instantiate an abstract class.
Some say when ever object is created, the constructor is called. But when we instantiate a subclass of an abstract class, the abstract class-constructor is called. I believe if a constructor is called, it doesn't mean that the Object is created. My question is: How can we confirm that the object is created:

我们都知道我们不能实例化一个抽象类。有人说,当创建对象时,会调用构造函数。但是当我们实例化抽象类的子类时,会调用抽象类构造函数。我相信如果调用构造函数,它并不意味着创建了Object。我的问题是:我们如何确认对象是否已创建:

public abstract class One
{
    public One()
    {
        System.out.println("One Object Constructor ");
    }

    public void test()
    {
    }

    public void testTwo()
    {
        System.out.println("Test Two");
    }
}

public class Two extends One
{
    public Two()
    {
        System.out.println("This is Two");
    }

    public static void main(String[] args)
    {
        Two t = new Two();
    }
}

Output:

One Object Constructor
This is Two

一个对象构造函数这是两个

1 个解决方案

#1


A constructor is always called when an object/instance is created. If you have a class without a constructor it will in fact have a constructor that takes no arguments and calls a similar no-argument constructor in the superclass.

在创建对象/实例时始终会调用构造函数。如果你有一个没有构造函数的类,它实际上会有一个不带参数的构造函数,并在超类中调用一个类似的无参数构造函数。

In addition all classes must call their superclass constructors, explicitly or implicitly (an implicit call only works if the superclass has a no-arguments constructor), so you can be sure that a constructor for each class in the chain has been called.

此外,所有类必须显式或隐式地调用其超类构造函数(隐式调用仅在超类具有无参数构造函数时才有效),因此您可以确保已调用链中每个类的构造函数。

Perhaps you meant that in the constructor for One you cannot be sure that the actual instance has class One, it might also be a subclass? If so you can verify with getClass(), which returns the actual class.

也许你的意思是在One的构造函数中你不能确定实际的实例是否有类One,它也可能是一个子类?如果是这样,您可以使用getClass()进行验证,该类返回实际的类。

#1


A constructor is always called when an object/instance is created. If you have a class without a constructor it will in fact have a constructor that takes no arguments and calls a similar no-argument constructor in the superclass.

在创建对象/实例时始终会调用构造函数。如果你有一个没有构造函数的类,它实际上会有一个不带参数的构造函数,并在超类中调用一个类似的无参数构造函数。

In addition all classes must call their superclass constructors, explicitly or implicitly (an implicit call only works if the superclass has a no-arguments constructor), so you can be sure that a constructor for each class in the chain has been called.

此外,所有类必须显式或隐式地调用其超类构造函数(隐式调用仅在超类具有无参数构造函数时才有效),因此您可以确保已调用链中每个类的构造函数。

Perhaps you meant that in the constructor for One you cannot be sure that the actual instance has class One, it might also be a subclass? If so you can verify with getClass(), which returns the actual class.

也许你的意思是在One的构造函数中你不能确定实际的实例是否有类One,它也可能是一个子类?如果是这样,您可以使用getClass()进行验证,该类返回实际的类。