java - Is it unnecessary to put super() in constructor? -


isn't 1 automatically put compiler if don't put in subclass's constructor?

that means don't need care it? in articles put out.

and if i've got 1 constructor arguments, constructor, or take constructor without argument list?

firstly terminology:

  • no-args constructor: constructor no parameters;
  • accessible no-args constructor: no-args constructor in superclass visible subclass. means either public or protected or, if both classes in same package, package access; and
  • default constructor: public no-args constructor added compiler when there no explicit constructor in class.

so classes have @ least 1 constructor.

subclasses constructors may specify first thing constructor in superclass invoke before executing code in subclass's constructor.

if subclass constructor not specify superclass constructor invoke compiler automatically call accessible no-args constructor in superclass.

if superclass has no no-arg constructor or isn't accessible not specifying superclass constructor called (in subclass constructor) compiler error must specified.

for example:

public class base { } public class derived extends base { } 

this fine because if add no constructor explicitly java puts in public default constructor you.

public class base { } public class derived extends base { public derived(int i) { } } 

also fine.

public class base { public base(string s) { } } public class derived extends base { } 

the above compilation error base has no default constructor.

public class base { private base() { } } public class derived extends base { } 

this error because base's no-args constructor private.


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -