Java Constructor explanation
Here you go Saran ✨—13-marks combined answer with clear explanation + simple
programs.
(i) What is Java Constructor?
(7 Marks)
Definition
A constructor in Java is a special method that is automatically called when an object
is created.
It is used to initialize objects, i.e., to assign initial values to instance variables.
Features of Constructor
1. Constructor name must be same as class name.
2. It has no return type, not even void.
3. It is executed automatically when new keyword is used.
4. There are two types:
Default Constructor
Parameterized Constructor
Example Program
1. Default Constructor
java
class Student {
int id;
String name;
// Default constructor
Student() {
id = 1;
name = "Saran";
}
1/5
void display() {
[Link](id + " " + name);
}
public static void main(String[] args) {
Student s = new Student(); // constructor called automatically
[Link]();
}
}
2. Parameterized Constructor
java
class Student {
int id;
String name;
// Parameterized constructor
Student(int i, String n) {
id = i;
name = n;
}
void display() {
[Link](id + " " + name);
}
public static void main(String[] args) {
Student s = new Student(101, "Arun");
[Link]();
}
}
Output
101 Arun
2/5
(ii) Discuss Java Access Specifiers with Example.
(6 Marks)
Access specifiers define visibility of classes, variables, methods, and constructors.
Java provides four access specifiers:
1. public
Accessible from anywhere in the program.
Example:
java
public class Demo {
public int a = 10;
public void display() {
[Link]("Public Method");
}
}
2. private
Accessible only within the same class.
Cannot be accessed outside the class.
Example:
java
class Demo {
private int data = 50;
private void show() {
[Link]("Private Method");
}
}
3/5
3. protected
Accessible:
inside the same class
within the same package
in subclasses (even in different packages)
Example:
java
class A {
protected int x = 30;
}
4. Default (no keyword)
Accessible only within the same package.
Example:
java
class Test {
int num = 20; // default access
}
Simple Program Showing All Access Specifiers
java
package pack1;
public class A {
public int a = 10;
private int b = 20;
protected int c = 30;
int d = 40; // default
public void display() {
4/5
[Link]("Public: " + a);
[Link]("Private: " + b);
[Link]("Protected: " + c);
[Link]("Default: " + d);
}
}
package pack2;
import pack1.A;
class B extends A {
public static void main(String[] args) {
B obj = new B();
[Link](obj.a); // public
[Link](obj.c); // protected
// obj.d -> ERROR (default)
// obj.b -> ERROR (private)
}
}
Perfect 13-Marks Points Coverage
✔ Definition
✔ Types of constructors
✔ Example programs
✔ Features of constructors
✔ All four access specifiers
✔ Simple, clean examples
✔ Inheritance coverage for protected
If you want, I can also prepare this as a PDF 📄.
5/5