I have the following class:
public class B {
public void print() {
}
public static void main(String[] args) {
B B = new B();
B.print();
}
}
I was wondering why the compiler didn’t give an error saying it’s not a static method. How will it distinguish between the class level and instance level when we have the object with the same as the class?
Because you are accessing the method on an instance of the class. Incidentally the name of the instance is the same as the class name, but since you don’t have a static method with this name, the compiler assumes the correct – i.e. an instance method.
If you define the method to be
static, then it will again assume the only possible thing – calling astaticmethod on theBclass, because the instance doesn’t have such a method.And ultimately, you can’t have both a
staticand a non-staticmethod with the same name.