new keyword, at least one constructor is called.
access-modifiers ClassName(list of parameters)
{
//body
}
public class Test
{
//constructor
public Test()
{
//body
}
public static void main(String[] args)
{
Test t = new Test(); //constructor called automatically when we create object
}
}
void).
public, private, protected or default) but cannot have non-access modifiers like static, final, abstract etc.
class ClassName
{
// Default constructor is automatically provided by Java Compiler
}
public class Test
{
//here programmer didnt created any constructor, so Java compiler will create default constructor automatically.
public static void main(String[] args)
{
Test t = new Test(); //default constructor called automatically when we create object
}
}
super()).
public Test()
{
super();
}
class ClassName
{
// No-Argument Constructor
ClassName()
{
// Initialization code (if needed)
}
}
public class Student
{
String name;
// No-Argument Constructor
Student()
{
name = "Deepak"; // Assigning default value
}
void display()
{
System.out.println("Student Name: " + name);
}
public static void main(String[] args)
{
Student s1 = new Student(); // Calls no-argument constructor
s1.display(); // Output: Student Name: Deepak
}
}
class ClassName
{
ClassName(dataType parameter1, dataType parameter2)
{
// Initialization code
}
}
class Student
{
String name;
int rollno;
// Parameterized Constructor
Student(String n, int rn)
{
name = n;
rollno = rn;
}
void display()
{
System.out.println("Name: " + name + ", Roll No.: " + rollno);
}
public static void main(String[] args)
{
Student s1 = new Student("Deepak", 101); // Passing values
s1.display(); // Output: Name: Deepak, Roll No.: 101
}
}
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.