@@ -9,10 +9,11 @@ constructor of the object's actual class type, but also the constructor of each
99Suppose there is a ` Horse ` class which extends ` Animal ` (and obviously ` Animal ` extends ` Object ` ). Now this is how the
1010constructors are called after ` new Horse() ` is invoked from ` main() ` :
1111
12- 1 . main() calls new Horse()
13- 2 . Horse() calls super()
14- 3 . Animal() calls super()
15- 4 . Object()
12+ -----------------------------|
13+ 1 . main() calls new Horse() |
14+ 2 . Horse() calls super() |
15+ 3 . Animal() calls super() |
16+ 4 . Object() |
1617
1718
1819Constructors __ have no return type__ and their __ names must exactly match the class name__ . Typically, constructors
@@ -30,9 +31,100 @@ class Foo {
3031}
3132{% endhighlight %}
3233
34+ So when you invoke __ ` new Foo("rohit", 12) ` __ , an object of ` Foo ` class is created with ` name ` set as ` Rohit ` and ` size `
35+ as ` 12 ` .
3336
37+ ### Below are the important rules for Constructors:
3438
39+ __ 1.__ If you don't type a constructor into your class code, a default constructor will be automatically generated by
40+ the compiler. The default constructor is ALWAYS a no-arg constructor.
3541
42+ <table >
43+
44+ <tr >
45+ <th >
46+ Class Code (WhatYouType)
47+ </th >
48+ <th >
49+ Compiler Generated Constructor Code
50+ </th >
51+ </tr >
52+
53+
54+
55+ <tr >
56+ <td >
57+ {% highlight java %}
58+ class Foo {
59+
60+ }
61+ {% endhighlight %}
62+ </td >
63+ <td >
64+ {% highlight java %}
65+ class Foo {
66+ Foo() {
67+ super();
68+ }
69+ }
70+ {% endhighlight %}
71+ </td >
72+ </tr >
73+
74+
75+ <tr >
76+ <td >
77+ {% highlight java %}
78+ public class Foo {
79+
80+ }
81+ {% endhighlight %}
82+ </td >
83+ <td >
84+ {% highlight java %}
85+ public class Foo {
86+ public Foo() {
87+ super();
88+ }
89+ }
90+ {% endhighlight %}
91+ </td >
92+ </tr >
93+
94+
95+ </table >
96+
97+ __ 2.__ Every constructor has, as its first statement, either a call to an overloaded constructor (` this() ` ) or a call to the
98+ superclass constructor (` super() ` ), and if not it is inserted by the compiler.
99+
100+
101+ <table >
102+
103+ <tr >
104+ <td >
105+ {% highlight java %}
106+ class Foo {
107+ Foo() { }
108+ }
109+ {% endhighlight %}
110+ </td >
111+ <td >
112+ {% highlight java %}
113+ class Foo {
114+ Foo() {
115+ super();
116+ }
117+ }
118+ {% endhighlight %}
119+ </td >
120+ </tr >
121+
122+ </table >
123+
124+ __ 3.__
125+
126+
127+ {% include responsive_ad.html %}
36128
37129### Q&A
38130
0 commit comments