0% found this document useful (0 votes)
3 views3 pages

Understanding Java Constructors

A constructor in Java is a special method used to initialize objects when a class is instantiated. It can set initial values for object attributes, and can also take parameters to initialize these attributes. Examples illustrate both a default constructor and a parameterized constructor that assigns values to class attributes.

Uploaded by

faizanhameed690
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views3 pages

Understanding Java Constructors

A constructor in Java is a special method used to initialize objects when a class is instantiated. It can set initial values for object attributes, and can also take parameters to initialize these attributes. Examples illustrate both a default constructor and a parameterized constructor that assigns values to class attributes.

Uploaded by

faizanhameed690
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Constructors

A 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:

Example
Create a constructor:

// 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)

[Link](myObj.x); // Print the value of x

// Outputs 5
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);

[Link](myObj.x);

// Outputs 5

You might also like