Java: Self for static method calls within the same class
Asked Answered
K

2

8

Is it possible to do something like self:: in PHP to not need to specify the class-name tro call a static method within the same class. See how I do it:

public class Foo
 public static void blaa() {...}
 public void foobar
 {
    Foo.blaa();
 }

but I'd like to it like

public class Foo
 public static void blaa() {...}
 public void foobar
 {
    _SOME_SORT_OF_SELF_.blaa();
 }

to not have to write down the classname over and over again... same would go for static attributes. Instead of using Foo.MY_ATTR maybe accessing it via _SOME_SORT_OF_SELF_.MY_ATTR.

Possible? Thanks

Kushner answered 27/3, 2014 at 22:55 Comment(4)
You know, use no prefix, it will work.Cleliaclellan
You can use blaa(). WIthout any prefix. I find it clearer with Foo.blaa(), but you're not forced to add the class name if it's the current class.Nodule
oh well, didn't know that. thanks. but yeah, it makes it a bit clearer to keep adding the class-name. but I'd even more like it via self. Same goes for attributes I suppose?Kushner
Yes, same for attributes. Non final static attributes are a design smell, though.Nodule
C
13

If you're trying to call a static method within the class it's defined in, you don't need to specify the type. (The rules get a little more complicated with nested classes).

For instance methods and variables, you can use the this keyword in your field access and method invocation expressions.

Cerracchio answered 27/3, 2014 at 22:56 Comment(0)
L
1
 class Solution{
  public static void main(String[] args) {
    String a = "Hello";
    String b = "World";
    
    System.out.println(addTwoString(a,b));
  }
  public static String addTwoString(String a,String b){
     return a+" "+b;
  }
}
Lovejoy answered 24/1 at 11:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.