@@ -34,7 +34,7 @@ class Foo {
3434So when you invoke __ ` new Foo("rohit", 12) ` __ , an object of ` Foo ` class is created with ` name ` set as ` Rohit ` and ` size `
3535as ` 12 ` .
3636
37- ### Below are the important rules for Constructors:
37+ ### Below are the important rules for Constructors
3838
3939__ 1.__ If you don't type a constructor into your class code, a default constructor will be automatically generated by
4040the compiler. The __ default constructor (the one supplied by compiler) is ALWAYS a no-arg constructor__ .
@@ -215,6 +215,62 @@ fail. In fact, the compiler won't even compile the code on the left hand side.
215215You can solve this in two ways, either you can provide a _ no-arg_ constructor in ` Animal ` class or you can
216216yourself type ` super("some name") ` as first statement in the constructor in ` Horse ` class.
217217
218+ __ 6.__ You cannot make a call to an instance method, or access an instance variable, until after the super constructor
219+ runs. __ Only static variables and methods can be accessed as part of the call to super() or this()__ .
220+
221+ <table >
222+
223+ <tr >
224+ <td >
225+ {% highlight java linenos %}
226+ public class Animal {
227+ String name;
228+
229+ Animal(String name) {
230+ this.name = name;
231+ }
232+
233+ Animal() {
234+ this(getName()); // ok!
235+ this(getNickName()); // compiler error!
236+ getNickName(); // ok!
237+ }
238+
239+ static String getName() {
240+ return "Horse";
241+ }
242+
243+ String getNickName() {
244+ return "Horsie";
245+ }
246+ }
247+ {% endhighlight %}
248+ </td >
249+ </tr >
250+
251+ </table >
252+
253+ Now let's understand the above code:
254+
255+ * line 9 is ok as the method ` getName() ` is static so it belongs to the class and can be accessed without
256+ the need of any object of the class.
257+ * line 10 is not ok as the method ` getNickName() ` is not static and to access such a method you need an object first and
258+ from constructor chaining we know that until and unless super type constructors are called object isn't created.
259+ * line 11 is fine because super type constructors are called before calling ` getNickName() ` .
260+
261+ ### Some more obvious rules which you already know but is worth mentioning
262+
263+ __ 7.__ __ Abstract classes have constructors__ , and those constructors are always called when a concrete subclass is
264+ instantiated.
265+
266+ __ 8.__ __ Interfaces do not have constructors__ . Interfaces are not part of an object's inheritance tree.
267+
268+ __ 9.__ A __ constructor can be invoked from within another constructor only__ . You cannot invoke a constructor
269+ from anywhere else.
270+
271+ __ 10.__ Lastly, __ constructors are never inherited__ . They aren't methods. __ Constructors can't be overridden__ (because
272+ they aren't methods and only instance methods can be overridden).
273+
218274{% include responsive_ad.html %}
219275
220276### Q&A
0 commit comments