Constructor.Are you confused about it . don't worry . Ok let's see the code
public class Students {
String name;
int age;
}
public static void main(String[] args) {
// write your code here\
var s1=new Students();
var s2=new Students();
}
}
ok now I ask s1 " what is your name and your age ". It will tell My name is null and my age is 0. then I ask s2" what is your name and your age ". it will tell "My name is null and my age is 0."
Oh my god I am confused
here you must know
name and age are instance variables.Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is null. Values can be assigned during the declaration or within the constructor
Here is the solution,
ok now we are moving on our chapter
Constructor
Here we have added code
Students(String name,int age)
{
this.name=name;
this.age=age;
}
this is constructor
don't panic . i will explain,
first you have to know
Students s1=new Students();
here the new keyword is going to create an object and that time JVM also provides value for name as null and age as0.Students().This means calling the constructor hence it is going to initialize the object this is we called constructor .
you can see this.name=name
here this means current object.
so when I create an object like
Students s1=new Students("karan",22);
it set the name as "karan"
and set the age 22
so the constructor initializes the object.
so I think you might understand the constructor usage
so what are the conditions we should follow to create constructor
- Constructor name must be the same as its class name.
- ok you can see I create constructor name Students . it is also class name.
- A Constructor must have no explicit return type.
- A Java constructor cannot be abstract, static, final, and synchronized.
- so can I put public in front of constructor . yaa sure when we put public .it will work anywhere
0 Comments