1class Other{
2 public Other(String message){
3 System.out.println(message);
4 }
5}
6
7class scratch{
8 public static void main(String[] args) {
9 Other method = new Other("Hey");
10 //prints Hey to the console
11 }
12}
1A constructor is a special method used to initialize objects in java.
2we use constructors to initialize all variables in the class
3when an object is created. As and when an object
4is created it is initialized automatically with the help of
5constructor in java.
6
7We have two types of constructors:
8Default Constructor
9Parameterized Constructor
10
11public classname(){
12}
13public classname(parameters list){
14}
1public class ConsDemo {
2 public static void main(String args[]) {
3 MyClass t1 = new MyClass();
4 MyClass t2 = new MyClass();
5 System.out.println(t1.num + " " + t2.num);
6 }
7}
1A constructor is a special method used to initialize objects in java.
2we use constructors to initialize all variables in the class
3when an object is created. As and when an object
4is created it is initialized automatically with the help of
5constructor in java.
6
7We have two types of constructors:
8Default Constructor
9Parameterized Constructor
10
11public classname(){
12}
13public classname(parameters list){
14}
15constructor calls:
161. only constructor can call other constructor
172. constructor cannot be called by its name, this() is used for calling
183. constructor call needs to be at the first step
194. One constructor can only call one constructor
205. Contractor cannot call itself or contain itself
21
1Constructors are the special methods without any return type.
2Constructors have the same name with the className
3Constructors are special methods, which are called
4whenever the new keyword is used to create an object of a class
5By default every class always has a default constructor
6with no parameters. This default constructor is no longer there if a
7constructor is created manually
8Constructors usually act to initialize instance variables or perform
9actions that need to be taken whenever an object of a class is created.
10Like methods, constructors can also be overloaded.
11The same rules apply. This is done by providing a constructor with
12with a different parameters
13this() can be used to call the overloaded
14constructors with other parameters
15