Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why are the class and method names the same?

I have just started learning Java. today, during training, I saw some code that had the same method and class name. I wanted to know how such a thing is possible? does the (public Animal) part work as a method here?

public class Animal {
    public Animal() {
        System.out.println(“I am an Animal”);
    }
}

In fact, I never expected that the name of the Class and the Method are the same.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Animal in this case isn’t technically a method – it’s a constructor – a special function that’s called when you construct an instance using the new operator.

You can recognize it by the fact it shares the name of the class and has no return type.

Having said that, you definitely can have a method with the same name as the class the contains it. It’s a bad practice because it may confuse people reading the code to think it’s a constructor, but it’s 100% possible.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading