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

后端 未结 11 1806
旧时难觅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:00
    1. No we can't use a constructor out of class because sub class is treat constructor as a method.. without return type.
    2. You can use it as a private but if a constructor of a class is private then you cannot make the obj of the respected class into another class.
    0 讨论(0)
  • 2020-12-29 15:01

    try this : http://www.javabeginner.com/learn-java/java-constructors 1 -> No 2 -> yes

    0 讨论(0)
  • 2020-12-29 15:02

    You can not override a constructor, however you can make them any access level modifier such as public, private or default. You would want a private constructor for things like a singleton or for a class that's mostly made of static methods and such (i.e Java's Math class)

    0 讨论(0)
  • 2020-12-29 15:04

    You can use callback:

    In parent class:

    protected void onCreate(){}
    
    SomeClass(){
    //Constructor code
    onCreate()
    }
    

    in child:

    @Override
    protected void onCreate(){
    //Child constructor code
    }
    
    0 讨论(0)
  • 2020-12-29 15:06

    no we cannt override an construtor, For implementing Singleton pattren we should have a private construtor.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题