Why might one also use a blank constructor?

前端 未结 10 578
傲寒
傲寒 2020-12-16 04:59

I was reading some Java recently and came across something (an idiom?) new to me: in the program, classes with multiple constructors would also always include a blank constr

相关标签:
10条回答
  • 2020-12-16 05:10

    Default constructor is NOT mandatory.

    If no constructors defined in the class then default (empty) constructor will be created automatically. If you've provided any parametrized constructor(s) then default constructor will not be created automatically and it's better to create it by yourself. Frameworks that use dependency injection and dynamic proxy creation at runtime usually require default constructor. So, it depends on use cases of class that you write.

    0 讨论(0)
  • 2020-12-16 05:12

    That is NOT a copy constructor. Basically you want empty constructors when working with some framework. Shall there always be an empty constructor, of course, public or private, but at least it allows you to keep control of how the class is being (or not) instantiated.

    0 讨论(0)
  • 2020-12-16 05:13

    The default constructor is'nt a good pratice for the functional view. The default constructor is used if the object have a global visibility into a method: for example, you want log the actual state of a object in a try/catch you can code

    MyObejct myObject=null
    try{...
    }catch(Exception e){
        log.error(myObject);//maybe print null. information?
    }
    

    or do you prefer

    MyObejct myObject=new Object();
    try{...
    }catch(Exception e){
    log.error(myObject);//sure print  myobject.toString, never null. More information
    }
    

    ?

    Anotherway the create a EMPTY object have'nt a lot of logic, but instatiate a NULL object is harmuful in my opinion. You can read this post

    0 讨论(0)
  • 2020-12-16 05:25

    You want to create a blank constructor for the classes that extended this class and since it has been extended the class... the child now has super which references the class above it it's parent. In the event the child did not specify super(stuff)... the stuff inside to reference the other constructors to use it will now attempt to reference the empty constructor.

    I'm not sure what the error will be I am coding my first parent object relationship now and was looking up things here ha cheers.

    I guess I should add the moment you make a constructor that isn't the empty one you lose the default empty one so now super() which is default in the extended class won't have something to point to. Of course if you created the extended classes to take care of super by specifying on which gets rid of the default super() then you sidestep this but what if someone wants to use your class and extend from it and didn't realize there isn't an empty set when you could have just created one.

    This is my first post but wanted to take a crack from how I understand it.

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