Can a method have the same name as the class?

Java Programming Java8Object Oriented Programming

Yes, you can write a method in Java with method name same as class name. But it is not suggestable because of the following reasons −

  • Using upper case letter at the starting of the name of the method violates the coding conventions of Java for writing a methods name.
  • There is a chance of assuming such methods with constructors of the class.

Example

Live Demo

public class Sample {
   public void Sample(){
      System.out.println("This is a sample method");
   }
   public static void main(String args[]){
      Sample obj = new Sample();
      obj.Sample();
   }
}

Output

This is a sample method
raja
Published on 22-Apr-2018 17:42:00
Advertisements