Why i am not getting an error while having same name for class and method in java?? | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 10

Why i am not getting an error while having same name for class and method in java??

I tried this and the code compiled successfully!! How's this possible in Java? whereas in c# I got an error!! class MyClass { static void MyClass () { System.out.println("2"); } public static void main(String[ ] args) { MyClass.MyClass (); } }

6th Mar 2017, 3:21 PM
Anusha
Anusha - avatar
16 Réponses
+ 9
actually u made a constructor..
29th Mar 2017, 6:04 AM
Saumya
Saumya - avatar
+ 8
@Meharban: you are wrong, it is not a constructor, it is a static class method. @Anusha: in Java a method can has the same name as class has.
6th Mar 2017, 6:13 PM
Tamás Barta
Tamás Barta - avatar
+ 7
OMG Meharban, don't speak stupid please :( Do you see "new" in Anusha's question? Do you see "static void" before MyClass? Do you know what do they mean?
6th Mar 2017, 6:23 PM
Tamás Barta
Tamás Barta - avatar
+ 7
@tamás barta thank you for your answer!!
8th Mar 2017, 5:02 AM
Anusha
Anusha - avatar
+ 5
@ram Kumar yeah..I know I am violating naming convention. but still I just wanted to know whether it works!!And it did🤓
8th Mar 2017, 5:04 AM
Anusha
Anusha - avatar
+ 5
that's okey🤓@Meharban Singh
8th Mar 2017, 5:14 AM
Anusha
Anusha - avatar
+ 4
of course, it works.. but, don't you think that you're violating Java's name convention..?? only constructor can have same same as class... mean, a upper case starting letter n method to be an lower case..? constructor is non-static and implicitly void return type. the one you created is a separate method which could face no problem, mostly.. but still some compilers warn saying that name is same as a constructors.
8th Mar 2017, 4:57 AM
ram kumar
ram kumar - avatar
+ 4
oops, sorry I messed up :-( @anusha @ramKumar @Tamas
8th Mar 2017, 5:10 AM
Meharban Singh
Meharban Singh - avatar
+ 4
thanks 😓 @Anusha. By the way you seem to be Indian.Am i true?
8th Mar 2017, 5:37 AM
Meharban Singh
Meharban Singh - avatar
+ 3
hi
29th Mar 2017, 12:17 AM
Haseeb Ahmad Ishqzadda
Haseeb Ahmad Ishqzadda - avatar
+ 3
how r u
29th Mar 2017, 12:18 AM
Haseeb Ahmad Ishqzadda
Haseeb Ahmad Ishqzadda - avatar
+ 2
oo
8th Mar 2017, 5:25 AM
Gautam Rathore yogendar
+ 2
I
8th Mar 2017, 5:25 AM
Gautam Rathore yogendar
+ 1
hi
16th Mar 2017, 5:06 AM
Peter Johnson
Peter Johnson - avatar
0
because java allow to have same name of class and it's member method but c# not
29th Mar 2017, 6:45 PM
Yogesh Tyagi
Yogesh Tyagi - avatar
0
As long as the complete signatures are different Java allows same name for different methods/constructors.
10th Apr 2017, 11:40 PM
Dr Sinnathamby Mahesan
Dr Sinnathamby Mahesan - avatar