💻 Step 6:Constructor – 3rd hour +code

💡Constructor-

Learn with our youtube video – 12 Minutes

💡Definition-

Constructor is used to construct the objects.

💡-It initialize default or given values to object.

Syntax-

modifiers ClassName(parameters) {
//Constructor body
}

💡Rules of creation-

1- Constructor Name should be same as class name.

💡Rules of implementation-

1- constructor always should be followed by new keyword.

classesconst

💡Types of constructor-

1- Non Parameterized constructor
2– Parameterized constructor

💡1- Non Parameterized

💡(i)Default constructor-

Only when no constructor is created in class, compiler adds default constructor.

Syntax- created by compiler in compiled code-  constructorName(){
}

💡(ii) Manual Constructor-

Constructor created with no parameters.
It can have statements in constructor body.

Syntax - modifiers constructorName(){
Statements
}

💡2- Parameterized Constructor-

Constructor created with parameters.
It also can have statements in constructor body.

Syntax- modifiers constructotName(parameters) {
Statements
}

💡Methods-

method is a set of statements to perform operations

Syntax –

Modifiers returnType methodName(parameters) {
//statements
}

Note- ReturnType= datatypes + void

code samples are here

1-Program to use default constructor(automatic creation)-


package constructors3;

public class Const1 {

public static void main(String[] args) {
Const1 c1 = new Const1();
}
}

Run This Program ▶️

2-Program to create  manual constructor which prints “a” and then use this manual constructor –

package constructors3;

public class Const2 {

public Const2() {
System.out.println("a");
}

public static void main(String[] args) {
Const2 c1 = new Const2();
}
}

Run This Program ▶️

3-Program to create parameterized constructor which takes String s as parameter and then use it by giving “Got it” as argument –



package constructors3;

public class Const3 {

public Const3(String s) {
System.out.println(s);
}

public static void main(String[] args) {
Const3 name = new Const3("Got it");
}

}

Run This Program ▶️

 
4-Program to create more than 1 constructor with different parameters then use all constructors by giving arguments.



package constructors3;

public class Const4 {

public Const4(int i,String a) {
System.out.println(i+a);

}

public Const4(String a,int i) {
System.out.println(a+i);
}

public Const4(double h,char o) {
System.out.println(h+" "+o);
}

public static void main(String[] args) {
Const4 c = new Const4(6, "deep");
Const4 c1 = new Const4(65.45d, 'p');
Const4 c2 = new Const4("kaushik",10);
}
}

Run This Program ▶️

 

Interview Questions —

  • What is difference between parameterized and non parameterized constructor?
  • What is difference between constructor and method ?