Does C # and java have static type support?

I used the Singleton classes and the static method for a while and always wondered how nice it would be to have a separate type, which is a static type and cannot be created, but only has static methods!

It will be easy to read and also support.

for ex

public UtilType MyUtility
{
  public void Calculate(int x,int y)
  {
    return x+y;
  }
}

It MyUtilityshould not be stated here that only its methods can be accessed in a static way.

+3
source share
8 answers

Why doesn't C # and java support utility type?

, # Java, "utility". , , :

  • - OO-.

  • . , , .

  • , "", . Java, , ; .. no-arg.

, Java/#, , .

, :

  • , , / ..

  • Java/# .

  • , .

+1

# static:

public static class MyUtility
{
    public static void Calculate(int x,int y)
    {
        return x+y;
    }
}

var result = MyUtility.Calculate(1, 2);

.

-, , . - - , - . , , , .

.

+9

... ?

public static class MyUtility
{
    public static void Calculate(int x,int y)
    {
        return x+y;
    }
}

...

public class AnyOtherClass
{
     public void AnyOtherMethod()
     {
          MyUtility.Calculate(4,5);
     }
}
+5

, masher

public final class Utilities
{
 // private constructor
 private Utilities(){ }

 public static int add(int x, int y)
 {
  return x+y;
 }

 public static int subtract(int x, int y)
 {
  return x-y;
 }
}
+2

? ( Java)

public class Utilities
{
   private Utilities() {} //added in an edit after reading comments

   public static int add(int x, int y)
   {
      return x+y;
   }

   public static int subtract(int x, int y)
   {
      return x-y;
   }
}

() , ...

0

?

public class MyUtility
{
    private MyUtility ( )
    {
    }

    public static int calculate(int x,int y)
    {
        return x+y;
    }
}

Java 5+ .

...
import static MyUtility.calculate

...
void myMethod ( )
{
  int sum = calculate( 1, 2 );
}
0

( .

public enum Utilities {
   ; 

   public static int add(int x, int y) { 
      return x+y; 
   } 

   public static int subtract(int x, int y) { 
      return x-y; 
   } 
} 

: , , .

0

, , - . , , .

, , , .

static , . , , .

-1

Source: https://habr.com/ru/post/1733126/


All Articles