
Understanding Constructor
In Java, a constructor is a special method within a class that shares the same name as the class itself. It's invoked automatically when an object of the class is created. Constructors initialize the newly created object, typically by assigning initial values to its attributes. They may accept parameters and execute initialization tasks. Constructors have no return type, not even void. Overloading is supported, allowing multiple constructors with different parameter lists. They ensure proper object initialization and are fundamental in object-oriented programming for creating and setting up instances of classes.
A Constructor can be defined by using the following syntax:
// Constructor declaration
public ClassName() {
// Constructor body
// Initialization code or other tasks
}
// Other class members and methods
}
Question-1:Write a program with the following specification:
Class name: prime
Instant variables : int n
Member functions: Prime():constructor to initialize n.
Void input(int x): to assign n with x.
Void display(): to check and print weather number n is prime or not.
Solution:
OUTPUT:
Enter the no:
5
Prime
Question-2:.Write a program with the following specification:
Class name : factorial
Data members: int a
Member functions: factorial() : default constructor to initialize the data member.
Void input(int m) : to assign a with m
Void display() : to print factorial of the number.check and print weather number n is prime or not.
Solution:
OUTPUT:
Enter the no:
6
Factorial=720
Constructors in Java initialize objects by assigning initial values to their member variables. They share the class's name, have no return type, and can be overloaded. If no constructor is defined, Java provides a default one. Constructors can have access modifiers and can chain to one another. Understanding constructors is crucial for proper object initialization and flexible class design in Java programming. They ensure objects start in a valid state and facilitate various ways of object creation.