CONSTRUCTOR IN JAVA

Maha

CONSTRUCTOR IN JAVA

Constructor is a  special member function of a class which is automatically called whenever a new object is created.


Types of Java constructors:

There are two types of constructors in java are;

1. Default constructor.

2. Parameterized constructor.


1. Default Constructor:

A constructor is called "Default Constructor" when it doesn't have any parameter is know as default constructor.

Syntax:

class_classname()

{

}


Example;

class Table

{

Table()

{

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

}

public static void main(String args[])

{

Table b=new Table();

}

}

Output:

Table is created.


2. Parameterized Constructor:

A constructor which has a specific number of parameters is called a parameterized constructor.


Example:

public class Person 

{

private String name;

private int age;

public Person(String name, int age) 

{

this.name = name;

this.age = age;

}

public void printDetails() 

{

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

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

}

public static void main(String[] args)

{

Person person = new Person("Jessy", 30);

person.print

Details();

}

}

Output:

Name: Jessy

Age: 30

Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send