Loading content...
Loading content...
A constructor is a special type of method used to initialize class variables.
It is automatically called when an object is created.
Constructor name must be same as class name
No return type allowed
Cannot call constructor explicitly like a method
Executes automatically at object creation
Can have parameters like methods
java
class A {
A() {
System.out.println("Constructor in A class");
}
void A() {
System.out.println("This is a method, not constructor");
}
}
class Main {
public static void main(String[] args) {
A a1 = new A();
}
}A() → constructorvoid A() → normal method
java
class Student {
int sid;
String sname;
String email;
static String nationality;
Student(int id, String name, String email, String nat) {
sid = id;
sname = name;
this.email = email;
nationality = nat;
}
void show() {
System.out.println(sid + " " + sname + " " + email + " " + nationality);
}
}Created automatically by Java compiler if no constructor is defined
Default constructor is non-parameterized
If you create your own constructor → default constructor will NOT be created
Calling one constructor from another constructor
this()plaintext
class A {
A() {
System.out.println("No-arg constructor");
}
A(int a) {
this();
System.out.println("1-arg constructor");
}
A(int a, int b) {
this(10);
System.out.println("2-arg constructor");
}
}
class Main {
public static void main(String[] args) {
new A(10, 20);
}
}this():Must be first statement
Only one constructor call allowed
No cyclic calling
this is a reference variable that refers to the current object
Cannot be used in static context
Used to:
Access instance variables
Call constructors (this())
java
class Student {
int sid;
String name;
Student(int sid, String name) {
this.sid = sid;
this.name = name;
}
}this.sid → current object variable
java
class A {
void m1() {
System.out.println("this: " + this.hashCode());
}
}Shows current object reference
Allows passing multiple arguments dynamically
java
int... aWorks like array internally
Can pass any number of values
Must be last parameter
Only one var-arg allowed
java
class A {
void m1(int... a) {
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}
class Main {
public static void main(String[] args) {
A obj = new A();
obj.m1(10, 20, 30, 40);
}
}java
void m1(String s, int... a) {
System.out.println(s);
for (int i : a) {
System.out.println(i);
}
}