Constructor In Java Flashcards

1
Q

What are Constructor?

A

A method used to create Object.

constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes

Types of Constructor:
1.Default constructor: A constructor that take no parameters.
2.user defined constructor: constructor that take parameters.

Note that the constructor name must match the class name, and it cannot have a return type (like void).

Also note that the constructor is called when the object is created.

All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.

/ Create a Main class
public class Main {
int x; // Create a class attribute

// Create a class constructor for the Main class
public Main() {
x = 5; // Set the initial value for the class attribute x
}

public static void main(String[] args) {
Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
System.out.println(myObj.x); // Print the value of x
}
}

// Outputs 5

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Constructor Overloading

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Constructor Parameter

A

Constructor Parameters
Constructors can also take parameters, which is used to initialize attributes.

The following example adds an int y parameter to the constructor. Inside the constructor we set x to y (x=y). When we call the constructor, we pass a parameter to the constructor (5), which will set the value of x to 5:

Example
public class Main {
int x;

public Main(int y) {
x = y;
}

public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println(myObj.x);
}
}

// Outputs 5

How well did you know this?
1
Not at all
2
3
4
5
Perfectly