Can we override a constructor in Java and can a constructor be private?

后端 未结 11 1888
旧时难觅i
旧时难觅i 2020-12-29 14:21

I would appreciate an explanation for these questions:

  1. Can we Override a constructor in Java?
  2. Can a Constructor be private?<
11条回答
  •  难免孤独
    2020-12-29 15:07

    No, you can't override a constructor. They're not inherited. However, each subclass constructor has to chain either to another constructor within the subclass or to a constructor in the superclass. So for example:

    public class Superclass
    {
        public Superclass(int x) {}
    
        public Superclass(String y) {}
    }
    
    public class Subclass extends Superclass
    {
        public Subclass()
        {
            super(5); // chain to Superclass(int) constructor
        }
    }
    

    The implication of constructors not being inherited is that you can't do this:

    // Invalid
    Subclass x = new Subclass("hello");
    

    As for your second question, yes, a constructor can be private. It can still be called within the class, or any enclosing class. This is common for things like singletons:

    public class Singleton
    {
        private static final Singleton instance = new Singleton();
    
        private Singleton()
        {
            // Prevent instantiation from the outside world (assuming this isn't
            // a nested class)
        }
    
        public static Singleton getInstance() {
            return instance;
        }
    }
    

    Private constructors are also used to prevent any instantiation, if you have a utility class which just has static methods.

提交回复
热议问题