Calling static methods using an instance of that class

时间:2015-07-28 22:22:30

标签: java syntax static

I understand that to call static methods , we do not need an instance of a class. We can directly call it using the class name. For the code below:

Class Demo
{
  Integer instVariable;

  // Static method
  public static Integer someUtility(Integer arg)
  {
     // Perform some calculations and return the result back
  }

  // Non static method
  public void changeState()
  {
     // Change instance behaviour
  }
}

I can call the static method

Demo.someUtility(42);

Yet Java also allows the following syntax

Demo someRef = new Demo();
someRef.someUtility(42);

I am trying to understand why Java would support a syntax like this. Because someUtility is being called using a dot operator on a reference , it implies that this method has knowledge about the object that someRef is referencing (which it does not). It's just misleading.

I am just wondering if there were other considerations.

0 个答案:

没有答案