Java Constructors
A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes:
A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type.
Typically, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other start-up procedures required to create a fully formed object.
All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used.
Syntax
Following is the syntax of a constructor −
class ClassName { ClassName() { } }
Program without using constructors.
package com.ritesh;
class ts{
private int n1;
private int n2;
public int getN1(){
return n1;
}
public void setN1(int set1){
n1=set1;
}
public int getN2(){
return n2;
}
public void setN2(int set2){
n2=set2;
}
}
public class constructor {
public static void main(String[] args) {
ts key=new ts();
key.setN1(3);
key.setN2(4);
System.out.println(key.getN1());
System.out.println(key.getN2());
}
}
Program done using constructor..
package com.ritesh;
class ts{
private int n1;
private int n2;
public ts(){ //constructor
n1=20;
n2=30;
}
public int getN1(){
return n1;
}
public void setN1(int set1){
n1=set1;
}
public int getN2(){
return n2;
}
public void setN2(int set2){
n2=set2;
}
}
public class constructor {
public static void main(String[] args) {
ts key=new ts();
System.out.println(key.getN1());
System.out.println(key.getN2());
}
}
The job of the constructor is to ensure that the new object is in a valid state, usually by giving initial values to the instance variables of the object. So a "constructor" should really be called an "initializer."
Comments
Post a Comment