Issue
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.
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.
Answered By - Mureinik
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.