Posted by
Zhullyblog
on
- Get link
- X
- Other Apps
CONSTRUCTORS
In this tutorial, you would learn about constructurs in Java programming.
A constructor in Java is a block of code that is similar to a method that's invoked when an instance of an object is created .
Note:A constructor is not the same as a method but it's quite similar to method. A constructor must have the same name with the class name and must not return any value.
Take a look at this;
class Sample {
void Sample() {
// method body
}
}
Sample( ) Is a constructor. It has exactly the same name as the class name and have no return type. Let's take an example.
class Sample {
private int x;
// The constructor
private Sample(){
System.out.println("This is the constructor");
x = 5;
}
public static void main(String[] args){
// Here we will call the constructor
Sample obj = new Sample();
System.out.println("Value of x = " + obj.x);
}
}
Snippet
Types of constructor
There are two different types of constructor namely;
NO ARGUMENT
PARAMETERIZED
NO ARGUMENT:When a constructor does not accept parameters,it is known as NO ARGUMENT constructors. A NO ARGUMENT constructors is quite similar but entirely different from default constructor. The body of a default constructor is empty but a NO ARGUMENT can have any code.
Here is an example
class Main {
int x;
// constructor with no parameter
private Main(){
// body of the constructor
x = 5;
System.out.println("x = " + x);
}
public static void main(String[] args) {
// calling the constructor with no parameter
Main obj = new Main();
}
}
Screenshot
PARAMETERIZED:A constructor that accept a parameter is known as a parameterized constructor. Unlike the NO ARGUMENT constructor that doesn't accept any argument. Parameterized constructor accept argument. In parameterized constructor, the parameters to be added are declared inside the parenthesis after the constructors name.
Let's take an example
class Staff {
int code;
// constructor accepting single value
private Staff(int age){
this.code = code;
System.out.println(code + " staff .");
}
public static void main(String[] args) {
// calling the constructor by passing single value
Staff s1 = new Staff(2);
Staff s2 = new Staff(3);
Staff s3 = new Staff(4);
}
}
Screenshot
Summary
CONSTRUCTORS ARE INVOKED WHEN AN OBJECT IS CREATED
A CONSTRUCTOR MUAT HAVE THE SAME NAME AS CLASS
A CONSTRUCTOR MUST NOT HAVE RETURN TYPE
THERE AR SIMPLY TWO TYPES OF CONSTRUCTORS.
Introduction to Java programming
How to declare a variable in Java
If, if..else statement in Java
Java Object Oriented Programming
Please share
Comments
Post a Comment