`
A constructor is a special method used to initialize objects in Java. It is automatically called when an object is created.
void
).class Example {
int num;
String str;
// Default Constructor
Example() {
num = 0;
str = "Default";
}
}
class Example {
int num;
String str;
// Parameterized Constructor
Example(int num, String str) {
this.num = num;
this.str = str;
}
}
class Example {
int num;
String str;
// Copy Constructor
Example(Example other) {
this.num = other.num;
this.str = other.str;
}
}
class Singleton {
private static Singleton instance;
// Private Constructor
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
The static
keyword is used for memory management and defines members that belong to the class rather than to individual instances.
static
Can Be Used:class Example {
static int count = 0;
Example() {
count++;
}
}
class Example {
static void displayMessage() {
System.out.println("Static Method");
}
}
class Example {
static {
System.out.println("Static Block Executed");
}
}
static
can be accessed without an instance of the outer class.class Outer {
static class Nested {
void display() {
System.out.println("Static Nested Class");
}
}
}
The main method is static because the JVM needs to invoke it without creating an instance of the class. Since the program execution starts with the main method, it must be accessible without requiring an object.
public static void main(String[] args) {
// Program execution starts here
}
A static class in Java refers to a static nested class. It is a nested class that is declared static within an outer class.
class Outer {
static class StaticNested {
void display() {
System.out.println("Static Nested Class");
}
}
}
public class Main {
public static void main(String[] args) {
Outer.StaticNested nested = new Outer.StaticNested();
nested.display();
}
}
class Example {
int x;
Example() {
x = 0; // Default value
}
}
class Example {
int x;
Example(int value) {
x = value;
}
}
class Example {
int x;
Example(Example obj) {
this.x = obj.x;
}
}
class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}