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