Checkout our demo site to practice selenium https://magento.softwaretestingboard.com/

0 like 0 dislike
229 views
by

1 Answer

0 like 0 dislike
by New User (11 points)

Static keyword is widely used in programming. In Java, static keyword is used to create class level variables/methods and not instance (or object) level. Although there are other uses as well for example in creating static blocks, static inner classes, etc. 

Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier.

For example: Suppose you want to create a number of objects from Bicycle class and you want to assign a serial number to each Bicycle object uniquely. But you also want to have the total number of Bicycles which will continue increasing by 1 when you add a new bicycle object. In this case, you may make your serial number (which we discussed earlier) as non-static since it belongs to specific instance while you may want to keep total_number_of_bicycle as static since you want to store the number of total bicycles and add 1 continually. Your Bicycle class may look like:

public class Bicycle {

    protected int gear;

    protected String brand;

    private static int numberOfBicycles = 0;

    public Bicycle(int gear, String brand) {
        this.gear = gear;
        this.brand = brand;
    }

    public static void setNumberOfBicycles(int newNumberOfBicycles) {
        numberOfBicycles = newNumberOfBicycles;
    }
    
    public static int getNumberOfBicycles() {
        return numberOfBicycles;
    }
}

And, when you create an instance of this class, it may look like:

public class Hamilton {

    public static void main(String[] args) {
        int hamiltonGear = 6;
        String brand = "Hamilton";
        Bicycle hamilton = new Bicycle(hamiltonGear, brand);
        Bicycle.setNumberOfBicycles(Bicycle.getNumberOfBicycles()+1);
    }
}

Here, if numberOfBicycle was not static, we would not be able to retain (get) its previous state, since every time the object will be created, numberOfBicycle field will be initailized again.

Similarly, for methods - static methods need not be called through class objects, they can be referenced directly.

Also, since static variables/methods dont need object creation they help in memory management/optimization because no object creation - no memory allocation for the object/its methods/fields.

 

Further reads:

https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

https://www.journaldev.com/1365/static-keyword-in-java


This site is for software testing professionals, where you can ask all your questions and get answers from 1300+ masters of the profession. Click here to submit yours now!

...