2

How static method invoke without mentioning the class name?.ex-below

 class Test { 
   public static void staticMethodOne() {
       System.out.println("Static method one");
   }

   public void instanceMethodOne() {
   staticMethodOne();//Call static method without mentioning the class 
  //name 

   Test.staticMethodOne();//call from class name

   new Test().staticMethodOne();//calling from object ref
   }
   public static void staticMethodTwo() {
       staticMethodOne();
  }
}
charu joshi
  • 113
  • 12
  • Because you're calling it within the declaring class. – Mick Mnemonic Feb 27 '18 at 11:46
  • @MickMnemonic Guess, that is in other classes. Not in same class. – Suresh Atta Feb 27 '18 at 11:48
  • @ꜱᴜʀᴇꜱʜᴀᴛᴛᴀ, not sure I follow. What are you referring to? – Mick Mnemonic Feb 27 '18 at 11:48
  • @MickMnemonic I mean the duplicate you flagged. It's about static import and this question is about accessing within the class. – Suresh Atta Feb 27 '18 at 11:50
  • 1
    The question in the duplicate states "Can we call a static method without mentioning the class name in Java", so I would say it's an exact dupe. Also, the answers go to lengths in explaining Java's name resolution mechanism with proper JLS references. The highest-voted answer only covers static imports but the second one covers both use cases. I don't think anything added to this question provides more value to this topic. – Mick Mnemonic Feb 27 '18 at 11:52

2 Answers2

1

Since you are accessing it in the same class, you doesn't need an instance just like any other instance method.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

Any local method can be invoked without being qualified by class name (for static methods) or this keyword (for instance method) from within the same class, assuming that you don't call instance methods from static contexts.

Additionally, you can call static methods (almost) without qualifying them if you add a static import:

import static java.lang.String.format;

And in method

String formatted = format("this is format from %s", "String");
ernest_k
  • 44,416
  • 5
  • 53
  • 99