Confusion with class level and instance level

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 did not give an error saying that this is not a static method. How will it distinguish between class level and instance level if we have an object with the same class?

+3
source share
5 answers

Because you are accessing a method on an instance of a class. By the way, the instance name is the same as the class name, but since you do not have a static method with this name, the compiler assumes the correct method, i.e. Instance.

If you define a method as static, then it will again accept the only possible thing - calling the method staticin the class B, because the instance does not have such a method.

static static .

+5

JLS :

6.3.2

, , . § 6.5 , , . , . , .

, . :

class Test {
        static int x = 1;
        public static void main(String[] args) {
                int x = 0;
                System.out.print("x=" + x);
                System.out.println(", Test.x=" + Test.x);
        }
}

, JLS . "", .

+3

print()? , "" , , B.print(), B, B.

, , , . , , "b". :

public class B{

  public void print(){

  }

  public static void main(String[] args){

    B b = new B();

    b.print(); // This works
    B.print(); // this fails

  }

}
+2

print() - . B. :

public static void main(String[] args){
       print():
       }

print() .

, , . print() - , , . , B, B. , .

0

, ; , B.print() , .

, ;)

0

Source: https://habr.com/ru/post/1733385/


All Articles