Divesh Ps Exp 4
Divesh Ps Exp 4
in java.
Theory:
Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java
compiler creates a default constructor if your class doesn't have any
Rules for creating constructor There are two rules defined for the constructor. 1.
Constructor name must be the same as its class name 2. A Constructor must have no
explicit return type 3. A Java constructor cannot be abstract, static, final, and
synchronized
Default Constructor A constructor is called "Default Constructor" when it doesn't have
any parameter.
Syntax of default constructor: (){}
}
Example of default constructor
1. Java Default Constructor
//Java Program to create and call a default constructor
class Bike1
{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");
}
//main method
public static void main(String args[])
{
//calling a default constructor
Bike1 b=new Bike1();
}}
Output: Bike is created
class StudentData{
private int stuID;
private String stuName;
private int stuAge;
StudentData()
{
//Default constructor
stuID = 33;
stuName = "Divesh";
stuAge = 18;
}
StudentData(int num1, String str, int num2)
{
//Parameterized constructor
stuID = num1;
stuName = str;
stuAge = num2;
}
//Getter and setter methods
public int getStuID() {
return stuID;
}
public void setStuID(int stuID) {
this.stuID = stuID;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getStuAge() {
return stuAge;
}
public void setStuAge(int stuAge) {
this.stuAge = stuAge;
}