What is Difference between Static Variable and Static method and Static Class? [duplicate]

A static variable is a variable:

public static int whatever = 0;

A static method is a method:

public static void whatever() {}

A static class is a class:

public static class SomeInnerClass {}

(A class can only have the static modifier when it is nested inside another class)

Static variables and methods can be accessed from any other class, and aren’t tied to the instance of that class. For instance, say you have the following class:

public class SomeClass {
    public static int myInt = 0;

    public static int add(int one, int two) {
        return one + two;

From any other class, you can access the variable and method directly, without creating an instance of SomeClass:

SomeClass.myInt = 23;
int sum = SomeClass.add(SomeClass.myInt, 2); //this will equal 25

If the variable and method weren’t static, you’d have to first instantiate SomeClass and then reference that instance:

SomeClass someClass = new SomeClass();
someClass.myInt = 23;
int sum = someClass.add(someClass.myInt, 2); //this will equal 25

Static classes are used to separate a nested class from its parent and remove the dependency on that parent’s instance. Take the following code:

public class ParentClass {
    public class ChildClass {}

From another (non-child of Parent) class, you would be able to use:

ParentCLass parent = new ParentClass();

But you wouldn’t be able to do:

ChildClass child = new ChildClass(); //this won't compile if it's not in ParentClass

However, if ChildClass becomes static:

public class ParentClass {
    public static class ChildClass {}

You will be able to instantiate it from another (non-child of Parent) class:

ChildClass child = new ChildClass(); //this will compile when put in any class

I recommend reading some Java basics on how classes work: https://www.geeksforgeeks.org/classes-objects-java/

Browse More Popular Posts

Leave a Comment