What's the difference between calling through and object vs class

StackOverflow https://stackoverflow.com/questions/11354617

  •  19-06-2021
  •  | 
  •  

Вопрос

What's the difference between calling a method through an object vs a class.

for example the Class Bob

public class SecretNumber() {
    public static int secretNumber = 2;
    public static void changeSecretNumber(){
        secretNumber++;
    }
}

What would be the difference if i called it like an object

SecretNumber secretNumber = new SecretNumber();
secretNumber.changeSecretNumber();

vs calling it like this

SecretNumber.changeSecretNumber();

How would one method effect the other?

Это было полезно?

Решение

The result is the same.

You should call it by class name, not through the instance, because no dynamic dispatch happens.

Most compilers will give you a warning, if you do that, too. Some people argue that it should have been made a compile error.

Другие советы

In Java, unless a class method is "static", you can't call it except through an object instance.

Here's an example of a method where it would make sense to declare it "static":

http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

The second form isn't valid Java. You can only call methods on a class if they are declared static.

Calling a method through a class is a static method. Unless you declare the method a static method, the compiler will give you a compile error .

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top