-2

I have a class with static method which will be invoked from same class method and from other class using Class.staticmethod. something like this,

ClassA{
 public void method1(){
     ---
     ---
     method2();
 }
 public static void method2(){
    ---
    ---
 }
}

ClassB{
  public void call(){
    ClassA.method2(); //i have to invoke through static method.
  }
}

public void main(...){
 ClassA obj = new ClassA();
 obj.method1();
}

Is the code follow the standard (Section 10.2 of Java conventions)? or i should invoke ClassA.method2() in classA method1. Please dont say this is a duplicate, I have looked at the other questions, they don't talk about this scenario.

8
  • 3
    Funnily enough, the conventions you mention explicitly mention that the usage you describe is OK. Commented Apr 27, 2015 at 21:43
  • 1
    @Happy that's just code example to show OP's intentions. Commented Apr 27, 2015 at 21:44
  • 1
    @Makoto I agree - it is funny, since it actually really bad coding style ;-) Commented Apr 27, 2015 at 21:44
  • 1
    Your example code is consistent with the Java coding conventions document. However, although those conventions are widely adopted, it's incorrect to call them a "standard". Commented Apr 27, 2015 at 21:47
  • 1
    @LuiggiMendoza Yeah you probably right but never forget that some beginners can find this question, so it's valuable mentioning that. Commented Apr 27, 2015 at 21:47

1 Answer 1

2

As the conventions state (thanks to Makoto), you should refrain from using an object reference to call a static method. That means, do not do this:

someObject.staticMethod();

Instead, use the Class name like this:

SomeClass.staticMethod();

Of course, if you are calling the static method from within that class it is ok (and probably preferred) to do this:

staticMethod();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.