DEV Community

Avinash Kumar
Avinash Kumar

Posted on

Class and method can have same name?

Yes, it can have. When you write a function with a return type(it will be a constructor without a return type) and as the same name as the class name it becomes a general function of the class.

Example:-

`public class Test{
public static void main(String []arg){
A obj = new A();//Constructor call
obj.A(); // Method call
}
}

class A{
public A(){
System.out.println("In constructor");
}

public void A(){
    System.out.println("In method");
}
Enter fullscreen mode Exit fullscreen mode

}`

Output:-
In constructor
In method

Top comments (0)