- What are static members in Java? (Explains Static method & field with example)
- What are Static members in Java?
- Understanding Class Members
- Class Variables
- Class Methods
- Constants
- The Bicycle Class
- Static field and method in java
- Статические поля
- Статические константы
- Статические инициализаторы
- Статические методы
What are static members in Java? (Explains Static method & field with example)
In the previous article, we have explained How to compare Strings in Java but if you have just started programming in Java or you have intermediate knowledge in it, you may come across this question in your mind, what are the static members in java? How are they different from public members and when to use them?
So, in this post, I am going to answer these above questions or you can say, will try to give the best answer and I hope to give all the answers to your questions related to static members.
What are Static members in Java?
The class level members which have static keyword in their definition are called static members.
In Java, a static member is a member of a class that isn’t associated with an instance of a class. Instead, the member belongs to the class itself. As a result, you can access the static member without first creating a class instance.
Let me explain this with an example, suppose here is the class with non-static members
now to call the Above size() method, we need to create a Item Class object to access it like below
Item item = new Item(); int value = item.size(); System.out.println(value);
But, in Static methods, we don’t need to create any instance of class
Let’s take a look at example of Static method
public class StaticMemberProgram < static int StaticTotallength(String a, String b) < // Add up lengths of two strings. return a.length() + b.length(); >static int StaticAverageLength(String a, String b) < // Divide total length by 2. return StaticTotallength(a, b) / 2; >public static void main(String[] args) < // Call methods. int total = StaticTotallength("Golden", "Bowl"); int average = StaticAverageLength("Golden", "Bowl"); System.out.println(total); System.out.println(average); >>
Now as You can see in the above example to call methods StaticTotallength & StaticAverageLength , we didn’t create any class object.
The output of the above program will be
Few important points of the static keyword in Java
- All static members are identified and get memory location at the time of class loading by default by JVM in Method area.
- Only static variables get memory location, methods will not have separate memory location like variables.
- Static Methods are just identified and can be accessed directly without object creation.
- Static field: A field that’s declared with the static keyword, like this
private static int StaticCount; static private int StaticCount;
- You can use the keyword static in front of a field or method declaration.
- The static keyword may come before or after the access modifier.
Example:
Define a static member in MathUtil class
One of the best-known static method is main , which is called by the Java runtime to start an application. The main method must be static , which means that applications run in a static context by default.
Also, you can’t access a nonstatic method or field from a static method because the static method doesn’t have an instance of the class to use to reference instance methods or fields.
Another important point about static method is that, you can not override static method in Java. If you declare same method in sub class i.e. static method with same name and method signature.
It will only hide super class method, instead of overriding it. This is also known as method hiding in Java. What this means is, if you call a static method, which is declared in both super class and sub class, method is always resolved at compile time by using Type of reference variable.
Example:
class Van < public static void kmToMiles(int km)< System.out.println("Inside Parent class static method"); >> class MainCar extends Van < public static void kmToMiles(int km)< System.out.println("Inside Child class static method"); >> public class Demo < public static void main(String args[])< MainCar v = new MainCar(); v.kmToMiles(10); >> //Output Will be //Inside Parent class static method
I hope this explanation makes all the static member-related questions in java clear to you, if not feel free to ask a question in the comments or in questions section.
Understanding Class Members
In this section, we discuss the use of the static keyword to create fields and methods that belong to the class, rather than to an instance of the class.
Class Variables
When a number of objects are created from the same class blueprint, they each have their own distinct copies of instance variables. In the case of the Bicycle class, the instance variables are cadence , gear , and speed . Each Bicycle object has its own values for these variables, stored in different memory locations.
Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.
For example, suppose you want to create a number of Bicycle objects and assign each a serial number, beginning with 1 for the first object. This ID number is unique to each object and is therefore an instance variable. At the same time, you need a field to keep track of how many Bicycle objects have been created so that you know what ID to assign to the next one. Such a field is not related to any individual object, but to the class as a whole. For this you need a class variable, numberOfBicycles , as follows:
Class variables are referenced by the class name itself, as in
This makes it clear that they are class variables.
You can use the Bicycle constructor to set the id instance variable and increment the numberOfBicycles class variable:
public class Bicycle < private int cadence; private int gear; private int speed; private int id; private static int numberOfBicycles = 0; public Bicycle(int startCadence, int startSpeed, int startGear)< gear = startGear; cadence = startCadence; speed = startSpeed; // increment number of Bicycles // and assign ID number id = ++numberOfBicycles; > // new method to return the ID instance variable public int getID() < return id; >. >
Class Methods
The Java programming language supports static methods as well as static variables. Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as in
instanceName.methodName(args)
A common use for static methods is to access static fields. For example, we could add a static method to the Bicycle class to access the numberOfBicycles static field:
public static int getNumberOfBicycles()
Not all combinations of instance and class variables and methods are allowed:
- Instance methods can access instance variables and instance methods directly.
- Instance methods can access class variables and class methods directly.
- Class methods can access class variables and class methods directly.
- Class methods cannot access instance variables or instance methods directlythey must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.
Constants
The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.
For example, the following variable declaration defines a constant named PI , whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter):
static final double PI = 3.141592653589793;
Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so. By convention, the names of constant values are spelled in uppercase letters. If the name is composed of more than one word, the words are separated by an underscore (_).
Note: If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant. If the value of the constant in the outside world changes (for example, if it is legislated that pi actually should be 3.975), you will need to recompile any classes that use this constant to get the current value.
The Bicycle Class
After all the modifications made in this section, the Bicycle class is now:
public class Bicycle < private int cadence; private int gear; private int speed; private int id; private static int numberOfBicycles = 0; public Bicycle(int startCadence, int startSpeed, int startGear) < gear = startGear; cadence = startCadence; speed = startSpeed; >public int getID() < return id; >public static int getNumberOfBicycles() < return numberOfBicycles; >public int getCadence() < return cadence; >public void setCadence(int newValue) < cadence = newValue; >public int getGear() < return gear; >public void setGear(int newValue) < gear = newValue; >public int getSpeed() < return speed; >public void applyBrake(int decrement) < speed -= decrement; >public void speedUp(int increment) < speed += increment; >>
Static field and method in java
Кроме обычных методов и полей класс может иметь статические поля, методы, константы и инициализаторы. Например, главный класс программы имеет метод main, который является статическим:
public static void main(String[] args)
Для объявления статических переменных, констант, методов и инициализаторов перед их объявлением указывается ключевое слово static .
Статические поля
При создании объектов класса для каждого объекта создается своя копия нестатических обычных полей. А статические поля являются общими для всего класса. Поэтому они могут использоваться без создания объектов класса.
Например, создадим статическую переменную:
public class Program < public static void main(String[] args) < Person tom = new Person(); Person bob = new Person(); tom.displayId(); // 3 // изменяем Person.counter Person.counter = 8; Person sam = new Person(); sam.displayId(); // Person< private int id; static int counter=1; Person()< id = counter++; >public void displayId() < System.out.printf("Id: %d \n", id); >>
Класс Person содержит статическую переменную counter, которая увеличивается в конструкторе и ее значение присваивается переменной id. То есть при создании каждого нового объекта Person эта переменная будет увеличиваться, поэтому у каждого нового объекта Person значение поля id будет на 1 больше чем у предыдущего.
Так как переменная counter статическая, то мы можем обратиться к ней в программе по имени класса:
System.out.println(Person.counter); // получаем значение Person.counter = 8; // изменяем значение
Консольный вывод программы:
Статические константы
Также статическими бывают константы, которые являются общими для всего класса.
public class Program < public static void main(String[] args) < double radius = 60; System.out.printf("Radisu: %f \n", radius); // 60 System.out.printf("Area: %f \n", Math.PI * radius); // 188,4 >> class Math
Стоит отметить, что на протяжении всех предыдущих тем уже активно использовались статические константы. В частности, в выражении:
out как раз представляет статическую константу класса System. Поэтому обращение к ней идет без создания объекта класса System.
Статические инициализаторы
Статические инициализаторы предназначены для инициализации статических переменных, либо для выполнения таких действий, которые выполняются при создании самого первого объекта. Например, определим статический инициализатор:
public class Program < public static void main(String[] args) < Person tom = new Person(); Person bob = new Person(); tom.displayId(); // Person< private int id; static int counter; static< counter = 105; System.out.println("Static initializer"); >Person() < id=counter++; System.out.println("Constructor"); >public void displayId() < System.out.printf("Id: %d \n", id); >>
Статический инициализатор определяется как обычный, только перед ним ставится ключевое слово static . В данном случае в статическом инициализаторе мы устанавливаем начальное значение статического поля counter и выводим на консоль сообщение.
В самой программе создаются два объекта класса Person. Поэтому консольный вывод будет выглядеть следующим образом:
Static initializer Constructor Constructor Id: 105 Id: 106
Стоит учитывать, что вызов статического инициализатора производится после загрузки класса и фактически до создания самого первого объекта класса.
Статические методы
Статические методы также относятся ко всему классу в целом. Например, в примере выше статическая переменная counter была доступна извне, и мы могли изменить ее значение вне класса Person. Сделаем ее недоступной для изменения извне, но доступной для чтения. Для этого используем статический метод:
public class Program < public static void main(String[] args) < Person.displayCounter(); // Counter: 1 Person tom = new Person(); Person bob = new Person(); Person.displayCounter(); // Counter: 3 >> class Person < private int id; private static int counter = 1; Person()< id = counter++; >// статический метод public static void displayCounter() < System.out.printf("Counter: %d \n", counter); >public void displayId() < System.out.printf("Id: %d \n", id); >>
Теперь статическая переменная недоступна извне, она приватная. А ее значение выводится с помощью статического метода displayCounter. Для обращения к статическому методу используется имя класса: Person.displayCounter() .
При использовании статических методов надо учитывать ограничения: в статических методах мы можем вызывать только другие статические методы и использовать только статические переменные.
Вообще методы определяются как статические, когда методы не затрагиют состояние объекта, то есть его нестатические поля и константы, и для вызова метода нет смысла создавать экземпляр класса. Например:
public class Program < public static void main(String[] args) < System.out.println(Operation.sum(45, 23)); // 68 System.out.println(Operation.subtract(45, 23)); // 22 System.out.println(Operation.multiply(4, 23)); // 92 >> class Operation < static int sum(int x, int y)< return x + y; >static int subtract(int x, int y) < return x - y; >static int multiply(int x, int y) < return x * y; >>
В данном случае для методов sum, subtract, multiply не имеет значения, какой именно экземпляр класса Operation используется. Эти методы работают только с параметрами, не затрагивая состояние класса. Поэтому их можно определить как статические.