简体   繁体   中英

How can we confirm that object is created in java

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:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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