method name same as class name
Yes, in Java, you can have a method with the same name as the class name. Such methods are known as constructors. Constructors are special methods used to initialize objects of a class. They have the same name as the class and do not have a return type, not even void.
Table of Contents
Here’s an example demonstrating the use of a constructor with the same name as the class:
Example
```java
public class MyClass {
private int value;
// Constructor with the same name as the class
public MyClass(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static void main(String[] args) {
// Create an instance of MyClass using the constructor
MyClass obj = new MyClass(10);
System.out.println("Value: " + obj.getValue()); // Output: Value: 10
}
}
```
In this example, `MyClass` has a constructor with the same name as the class (`MyClass`). This constructor initializes the `value` field of the object. When an instance of `MyClass` is created using the `new` keyword (`MyClass obj = new MyClass(10);`), the constructor is invoked to initialize the object.