In Java, a constructor is a special method that is called when an object of a class is created. Constructors are used to initialize the state of an object, and they have the same name as the class.
Here is an example of a class with a constructor in Java:
public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } }
In this example, the Person
class has two private fields: name
and age
. It also has a constructor that takes two arguments: a String
for the name and an int
for the age. The constructor initializes the name
and age
fields with the values passed as arguments.
To create a new Person
object using the constructor, you can use the following code:
Person p = new Person("John", 30); System.out.println("Name: " + p.getName()); System.out.println("Age: " + p.getAge());
This will create a new Person
object with the name "John" and the age 30, and print the name and age to the console.