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

Java Constructors

A constructor in Java is a special method used to initialize objects, sharing the same name as the class and lacking a return type. There are two types of constructors: default constructors, which take no parameters, and parameterized constructors, which take parameters to initialize object attributes. Key points include that constructors can be overloaded and that Java provides a default constructor if none is defined.

Uploaded by

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

Java Constructors

A constructor in Java is a special method used to initialize objects, sharing the same name as the class and lacking a return type. There are two types of constructors: default constructors, which take no parameters, and parameterized constructors, which take parameters to initialize object attributes. Key points include that constructors can be overloaded and that Java provides a default constructor if none is defined.

Uploaded by

eliassannu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Constructors in Core Java

What is a Constructor in Java?

A constructor is a special method used to initialize objects. It has the same name as the class and

does not have a return type.

Types of Constructors in Java:

1. Default Constructor (No parameters)

2. Parameterized Constructor (With parameters)

1. Default Constructor

Syntax:

class ClassName {

ClassName() {

// code to initialize object

Example:

class Car {

Car() {

System.out.println("Car is created");

public static void main(String[] args) {

Car myCar = new Car(); // Constructor is called here


}

Output:

Car is created

Explanation:

- Car() is the constructor.

- It is automatically called when the object myCar is created.

2. Parameterized Constructor

Syntax:

class ClassName {

ClassName(parameter1, parameter2, ...) {

// use parameters to initialize

Example:

class Student {

String name;

int age;

// Parameterized constructor

Student(String n, int a) {
name = n;

age = a;

void display() {

System.out.println("Name: " + name + ", Age: " + age);

public static void main(String[] args) {

Student s1 = new Student("Elisha", 21);

s1.display();

Output:

Name: Elisha, Age: 21

Explanation:

- Constructor Student(String n, int a) is used to set values while creating object s1.

Important Points:

- Constructor name must be same as class name.

- No return type, not even void.

- Called automatically when an object is created.

- Constructors can be overloaded.

- Java provides a default constructor if none is defined.

You might also like