0

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.

Chiseled
  • 2,280
  • 8
  • 33
  • 59
  • 1
    You'd still have a warning but see http://stackoverflow.com/questions/610458/why-isnt-calling-a-static-method-by-way-of-an-instance-an-error-for-the-java-co – Alexis C. Jul 28 '15 at 22:24
  • @AlexisC. thanks for pointing it out. Sufficiently answers my question. – Chiseled Jul 28 '15 at 22:27

0 Answers0