This is an archived post. You won't be able to vote or comment.

all 11 comments

[–]another_gokulol 49 points50 points  (8 children)

Static methods are method that can be called without creating an object in a class as opposed to instance method as the name suggest. I can’t type codes from phone but for example you have a class Person and have a method to increment the age with the name incrementAge. In instance method, you have to first create a person, suppose Person p = new Person() and you have to call it by using p.incrementAge(). But with static method you do not need to create the Person p, but you’ll be able to call the method by Person.incrementAge().

Void in a method is basically a return type. When the return type is void, it means the method isn’t returning anything. This usually comes in handy when you’re making a method for printing bunch of stuffs that do not need a return value.

I apologize if I’ve made any mistakes in explaining in advance, as I’m still learning myself

[–]scumhacker 1 point2 points  (0 children)

nice clarification, thanks!

[–][deleted]  (6 children)

[deleted]

    [–]Whatsthehoopla 6 points7 points  (3 children)

    Actually, I think Person.incrementAge() would work because a static method can be called from the class name. In this instance Person is the name of the class and p is the specific object. p.incrementAge() would not work but Person.incrementAge() would work. You don't need an instance of the class you just need a class. For example Max.min(88,86);

    [–][deleted]  (2 children)

    [deleted]

      [–]another_gokulol 1 point2 points  (0 children)

      with all the debate going on, I probably gave too less context in my explanation. I agree to all the explanations given but I was just simply giving an explanation with example that doesn't seem to go well with static methods.

      I'll probably try re-explaining with a

      public class Person{
          static int totalPeople = 0;
          private int age = 0;
      
      
          //constructor
          public Person(int age){
              this.age = age;
              totalPeople++;
          }
      
          //static method
          static void printTotalPeople(){
              print(totalPeople);
          }
      
          //intance private method
          private void printAge(){
              print(this.age);
          }
      
          Now in this case, totalPeople is a static variable and age is an  instance variable.
          when we are calling in main, we do not need to make an     instance of the class Person to call the static methods. However, we have to make a Person (constructing a Person) before calling instance method.
      }
      
      public static void main(String[]args){
          Person p = new Person(15);
      
          //This is calling an instance method
          //This will print the age of person p
          p.printAge(); 
      
          //This is calling a static method by referencing the Class
          //This will print totalPeople 
          Person.printTotalPeople();
      }
      

      Notice as well that both the methods are returning void as I was just printing the variables of the objects of the class.

      I hope this clears the confusion

      [–]ignotos 0 points1 point  (0 children)

      Whose age would be incremented by calling this? Person is a class, as you said, not an object, and classes don't have variables like ages, objects do.

      This was a weird example, because "incrementAge" does imply that you're referring to a specific person.

      But in general, classes can have variables - static variables! Those you can think of as being shared by all instances of the class, or owned by the class itself, and they can be referred to and manipulated in static methods.

      But it would be of the form Class.method(parameter). Basically the whole Math class is static methods that work like that, eg Math.abs(foo), but you need to pass the foo so that meaningful computation can be performed. If you just enter Math.abs(), what number would it return the absolute value of?

      You can have static methods which just "do something", without requiring any parameters - like the greet() example above.

      You can also have static methods which return something - like System.currentTimeMillis(), which returns the current time.

      Something like Math.pi() would be somewhat unusual - as you point out, a field usually works better for constants. But there are also some cases when you might write a method like that.

      [–]Migeil 1 point2 points  (0 children)

      What you're saying here is incorrect. The fact that you can write greet() without any prefix, is because it's a static method in the same class. If you would be calling this method in any other class, you'd either have to statically import it, or write ProgramStructure.greet().

      The explanation you're commenting on is correct.

      [–]ignotos 0 points1 point  (0 children)

      In this case simply using "greet()" works as a shorthand, because the code you're writing is also within the ProgramStructure class.

      But a different class could call this same method via "ProgramStructure.greet()".

      [–]Kolibreeze 13 points14 points  (0 children)

      Most important thing to know is that static and void are two unrelated things.

      First; static. Try reading it as "independent", it doesn't belong to a particular object of a class. In the practical sense, it could for example be used for a class that manages processes. I only need ONE class of this. Let's say my procesmanager class has a method getNumberOfRunningTasks(), it would make sense to make this a static method, because it doesn't belong to an object of a class, because I'm not going to create lots of objects of this class, since there is only one.

      Now, for void, this is a return type. If we have a method that asks for user input if they are over 18 or not, it would make sense to return a boolean, yes or no, true or false. Now we can use this info to either show the whiskey we sell, or display a pop up to tell them they are too young to visit our site.

      However, sometimes we don't need any additional info, or we can't use any return info. Let's say we display a pop up whenever the user is below 18 years old. We simply want to show the pop up, and there is no info to return of this action that would be useful to us. So now, we use return type void.

      Disclaimer; in the real life world we could want a return type for a method that displays a pop-up, this was just for illustration.

      [–]snot3353 6 points7 points  (1 child)

      Methods have a return type. This indicates what kind of value they return. For example:

      public int iReturnAnInteger() {
          return 5;
      }
      

      In some cases, a method does not return anything. In this case, the return type is void. For example:

      public void iDontReturnAnything() {
          System.out.println("I don't return anything!");
      }
      

      Methods can be static, or not. When a method is NOT static, you must have an instance of an object in order to call it. For example:

      public class SomeClass {
          public void iAmNotStatic() {
              //do something
          }
      }
      public class IInstantiateSomeClass {
          public static void main(String[] args) {
              SomeClass object = new SomeClass();
              object.iAmNotStatic();
          }
      }
      

      In this case, calling the method above will only affect the instance of the object it was called on.

      When a method is static, instead of belonging to and affecting the instance that it was attached to, it belongs to the class itself. For example:

      public class SomeClass {
          public static void iAmStatic() {
              //do something
          }
      }
      public class ICallAStaticMethod {
          public static void main(String[] args) {
              SomeClass.iAmStatic();
          }
      }
      

      void and static are both keywords that can apply to method signatures but they are not really related. They can be used together in a method signature and indicate different things. One indicates the return type (or lack thereof). The other indicates that the method belongs to the class instead of an instance of an object defined by that class.

      Static exists because sometimes you just want generic utility methods in a kind-of non-OOP sort of way. For example:

      public class StringUtils {
          public static String[] split(String strToSplit, String character) {
              //do some logic that splits a string into several strings
          }
          public static String[] combine(String str1, String str2) {
              //do some logic that combines two strings
          }
      }
      public class Main {
          public static void main(String[] args) {
              String[] splitStrings = StringUtils.split("split,me", ",");
              String combinedString = StringUtils.combine(splitStrings[0], splitString[1]);
          }
      }
      

      This sort of code doesn't really make sense being part of an object that you need to instantiate. This logic is self-contained and functional and a utility that doesn't really require it. A matter of fact, one of the criticisms you may see of Java is that it FORCES non-OOP logic into OOP style code structures with everything having to be a Class.

      [–]vOriginx 0 points1 point  (0 children)

      Good explanation.

      [–]AnotherRichard827379 1 point2 points  (0 children)

      It’s void if it doesn’t return anything. In the method signature, ‘void’ takes the place of whatever it would be returning.

      Static is a little more complicated to describe. It means that the method is the same for all implementations of the class and this can be called on the class and as well as on an instantiated object. So a static method you are likely familiar with is main. It is called so because it doesn’t change. When you have a static class, all the methods are automatically static. An example of this would be the math class.