Java constructors
Constructors in java are methods that are used to create new objects.They provide data to the object.
Note:
Note:
- Constructors have no return type.
- They are created using class name.
There are two types of Java Constructors.
- No argument or default constructor.
- Constructor with parameters.
Simple Java Default Constructor
public class Student {
Student()
{
System.out.println("A new Student created");
}
public static void main(String args[])
{
Student s =new Student();
}
}
Default constructor will provide null values or default to object
Example
public class Student {
String name;
int studentID;
void showDetails()
{
System.out.println("Student name is " +name);
System.out.println("Student ID is " +studentID);
}
public static void main(String args[])
{
Student s =new Student();
s.showDetails();
Student s2=new Student();
s2.showDetails();
}
}
Parameterized java constructor
A constructor with variables is called a parameterized constructors.They are used to give different values to object distinct.
Example:
public class Student {
String name;
int studentID;
Student(String s,int id)
{
name=s;
studentID=id;
}
void showDetails()
{
System.out.println("Student name is " +name);
System.out.println("Student ID is " +studentID);
}
public static void main(String args[])
{
Student s =new Student("Eric Mutua",222221);
s.showDetails();
Student s2=new Student("Jane Kate",232222);
s2.showDetails();
}
}
Output:
Student name is Eric Mutua
Student ID is 222221
Student name is Jane Kate
Student ID is 232222
BUILD SUCCESSFUL (total time: 0 seconds)
Student name is Eric Mutua
Student ID is 222221
Student name is Jane Kate
Student ID is 232222
BUILD SUCCESSFUL (total time: 0 seconds)