In Java, it is possible to define a method with the same name as the class itself. This type of method is called a constructor, and it is used to initialize objects of the class.
To define a constructor in Java, the method name must be the same as the class name. The constructor method does not have a return type, and its purpose is to allocate memory for an object of the class and to initialize its variables.
Here is an example of a constructor for a class named "Person":
public class Person { private String name; private int age; // Constructor method public Person(String name, int age) { this.name = name; this.age = age; } }
In this example, the constructor method has the same name as the class name "Person". It takes two parameters, a String "name" and an integer "age", which are used to initialize the corresponding variables of the object.
It's important to note that a class can have multiple constructors with different parameters, allowing for different ways to create objects of the class. However, in each case, the constructor method must have the same name as the class.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.