Constructors in java
Java Constructors
- Constructor is nothing but a method with a class name
- It doesn't return any values
- We don't write any return type of the constructor
- It is used to initialise the values when the object is created
- In java there is constructor called default constructor it is automatically initialize when there is no constructor is assigned
- We can also give parameters in the constructor so at the time of initialize we can assign some value into the class. It is known as parametric construction
- If we create a any constructor in a class then the default constructor will not work so we need to write the default constructor also if we want to use them
Ex:
1) Default constructor
class Hello{
public int a=10;
public int b=20;
}
class Hel{
public static void main (String []args){
Hello h=new Hello();// using default constructor
System.out.print(h.a+h.b);//1020
}
2) Constructor with no parameters
class Hello{
public Hello(){
System.out.print("Hello");
}
}
class Hel{
public static void main (String []args){
Hello h=new Hello();// calling constructor
//Output:Hello
}
}
3)Constructor with parameters
class Hello{
public int num;
public Hello(int num){
this.num=num;
}
}
class Hel{
public static void main (String []args){
Hello h=new Hello(10);// calling constructor with parameters
System.out.print(h.num);//10
// If we try to call the default constructor then it will raise an error
Hello d=new Hello()// error, since there is no default constructor available after we create a own construction
}
}
4) Creating 2 or more constructors
class Hello{
public int num=10;
public Hello(int num){
this.num=num;
}
public Hello(){}
}
class Hel{
public static void main (String []args){
Hello h=new Hello(60);// calling constructor with parameters
System.out.print(h.num);//60
Hello d=new Hello();
System.out.print(d.num);//10
}
}
Comments
Post a Comment