Static methods and static classes in java

Ключевое слово Static в Java — статические переменные, методы, классы и блоки.

Static — это ключевое слово в Java, которое можно применять к переменным, методам, классам и блокам. В этом посте представлен обзор поведения переменных, методов, классов и блоков кода в Java, когда к ним применяется ключевое слово static. Давайте подробно обсудим каждый из них:

1. Статические переменные

  1. Статические переменные также известны как переменные класса.
  2. Когда статический ключевое слово применяется к переменной, это означает, что переменная принадлежит классу, а не экземпляру класса.
  3. В памяти есть только одна копия статической переменной, которая используется всеми экземплярами класса.
  4. Статические переменные инициализируются перед любой из переменных экземпляра.
  5. Статические переменные можно использовать, когда какое-то значение необходимо разделить между всеми объектами класса. Чтобы гарантировать, что значение никогда не изменится после его инициализации, объявите статическую переменную как final.
  6. Доступ к статической переменной можно получить напрямую, используя имя класса, без создания экземпляра класса, в котором они определены. Используйте обозначение >.> для доступа к статической переменной. В пределах одного класса к ним можно получить прямой доступ.
  7. Стандартный выходной поток System.out отличный пример статической переменной в Java. Здесь out объявляется статическим в System учебный класс.
Читайте также:  Style float in javascript

Рассмотрим следующий код со статической переменной i определено в классе A . К нему можно получить прямой доступ по имени i внутри класса A и с A.i вне класса A .

Источник

Static methods and classes¶

A static method is a method that does not require an object to be created. Most often static methods are used if we want to execute the same algorithm in many places within the project.

Declaration¶

To declare a static method before the returned type , simply add the keyword static , such as:

Calling¶

To call the static method, we don’t need to create an instance of the object, but simply refer directly to the class, e.g:

It should be remembered that the abuse of static methods is a bad idea that will result in negative consequences very quickly. Firstly, we don’t write objective code at this point, which is in denial of the logic of using object language. Secondly, this way of writing code doesn’t allow us to use the potential of so-called Object Oriented Programming (OOP).

Static internal classes¶

What’s an internal class?¶

The easiest way to illustrate it is with an example:

In the above example, we are dealing with an external class called MyOuterClass and an internal class called MyInnerClass defined in MyOuterClass . Access modifiers used before the definition of an internal class work identically to attributes, methods or constructors. It should also be added that an internal class has access to all fields and methods of the external class (also private) in which it was defined.

Creating an internal class instance¶

To create an internal class instance we need an external class instance. This is illustrated by an example:

To refer to the MyOuterClass.MyInnerClass type is nothing more than to refer to the public internal type. In the example above, we have created instances of an internal class in two ways. The myInnerClass1 instance is created by calling the init() method on an instance of an external class myOuterClass — this method in turn calls the constructor of an internal class new in MyInnerClass() . We also create the myInnerClass2 instance using the myOuterClass instance, but here we openly call the internal class constructor, that is: myOuterClass.new MyInnerClass() .

What is a static internal class?¶

Let’s start with a simple example:

As can be seen in the example above, the only difference from a normal internal class is that the internal class declaration is preceded by a static modifier. It tells us that we are dealing with a declaration of static internal class. By default, all internal interfaces and enumeration types are static, the static modifier is redundant. What is important is the difference in creating an internal class static instance.

Creating an internal class static instance¶

Unlike the internal class, which is not static, you do not need an external class instance to create a static internal class instance. This is illustrated by an example:

We can see that it is enough to call the constructor using the static internal class type new in MyOuterClass.MyInnerClass() to create its instance.

When to use static internal classes?¶

If there is a reason why we want to have an internal class and simultaneously instance regardless of its external class, then it must be a static class.

Static fields¶

Declaration¶

Static fields are a class attribute, not an object. This means that it can be referenced without creating an object instance. To declare a static field, simply add a static modifier before declaring the type:

The myStaticNumber field will exist even if we do not create any instance.

Using static fields¶

Reference to a normal and static field is shown in the example below:

In the example above, in the line (1) we referred to the myStaticNumber variable based on the class type, not the instance of the object of that class. Attempting to refer to a non-static field myNumber without an object instance will result in a compilation error. The (2) example is a valid reference to an instance of the myNumber field.

Источник

static keyword in java

static keyword in java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

static keyword in Java is used a lot in java programming. Java static keyword is used to create a Class level variable in java. static variables and methods are part of the class, not the instances of the class.

static keyword in java

java static, static keyword in javaJava static keyword can be used in five cases as shown in below image. static keyword in java We will discuss four of them here, the fifth one was introduced in Java 8 and that has been discussed at Java 8 interface changes.

Java static variable

We can use static keyword with a class level variable. A static variable is a class variable and doesn’t belong to Object/instance of the class. Since static variables are shared across all the instances of Object, they are not thread safe. Usually, static variables are used with the final keyword for common resources or constants that can be used by all the objects. If the static variable is not private, we can access it with ClassName.variableName

 //static variable example private static int count; public static String str; public static final String DB_USER = "myuser"; 

Java static method

Same as static variable, static method belong to class and not to class instances. A static method can access only static variables of class and invoke only static methods of the class. Usually, static methods are utility methods that we want to expose to be used by other classes without the need of creating an instance. For example Collections class. Java Wrapper classes and utility classes contains a lot of static methods. The main() method that is the entry point of a java program itself is a static method.

 //static method example public static void setCount(int count) < if(count >0) StaticExample.count = count; > //static util method public static int addInts(int i, int. js)

Java static block

Java static block is the group of statements that gets executed when the class is loaded into memory by Java ClassLoader. Static block is used to initialize the static variables of the class. Mostly it’s used to create static resources when the class is loaded. We can’t access non-static variables in the static block. We can have multiple static blocks in a class, although it doesn’t make much sense. Static block code is executed only once when the class is loaded into memory.

Java Static Class

Let’s see all the static keyword in java usage in a sample program. StaticExample.java

package com.journaldev.misc; public class StaticExample < //static block static< //can be used to initialize resources when class is loaded System.out.println("StaticExample static block"); //can access only static variables and methods str="Test"; setCount(2); >//multiple static blocks in same class static < System.out.println("StaticExample static block2"); >//static variable example private static int count; //kept private to control its value through setter public static String str; public int getCount() < return count; >//static method example public static void setCount(int count) < if(count >0) StaticExample.count = count; > //static util method public static int addInts(int i, int. js) < int sum=i; for(int x : js) sum+=x; return sum; >//static class example - used for packaging convenience only public static class MyStaticClass < public int count; >> 

Let’s see how to use static variable, method and static class in a test program. TestStatic.java

package com.journaldev.misc; public class TestStatic < public static void main(String[] args) < StaticExample.setCount(5); //non-private static variables can be accessed with class name StaticExample.str = "abc"; StaticExample se = new StaticExample(); System.out.println(se.getCount()); //class and instance static variables are same System.out.println(StaticExample.str +" is same as "+se.str); System.out.println(StaticExample.str == se.str); //static nested classes are like normal top-level classes StaticExample.MyStaticClass myStaticClass = new StaticExample.MyStaticClass(); myStaticClass.count=10; StaticExample.MyStaticClass myStaticClass1 = new StaticExample.MyStaticClass(); myStaticClass1.count=20; System.out.println(myStaticClass.count); System.out.println(myStaticClass1.count); >> 

The output of the above static keyword in java example program is:

StaticExample static block StaticExample static block2 5 abc is same as abc true 10 20 

Notice that static block code is executed first and only once as soon as class is loaded into memory. Other outputs are self-explanatory.

Java static import

Normally we access static members using Class reference, from Java 1.5 we can use java static import to avoid class reference. Below is a simple example of Java static import.

package com.journaldev.test; public class A < public static int MAX = 1000; public static void foo()< System.out.println("foo static method"); >> 
package com.journaldev.test; import static com.journaldev.test.A.MAX; import static com.journaldev.test.A.foo; public class B < public static void main(String args[])< System.out.println(MAX); //normally A.MAX foo(); // normally A.foo() >> 

Notice the import statements, for static import we have to use import static followed by the fully classified static member of a class. For importing all the static members of a class, we can use * as in import static com.journaldev.test.A.*; . We should use it only when we are using the static variable of a class multiple times, it’s not good for readability. Update: I have recently created a video to explain static keyword in java, you should watch it below. https://www.youtube.com/watch?v=2e-l1vb\_fwM

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Ключевое слово Static в Java — статические переменные, методы, классы и блоки.

Static — это ключевое слово в Java, которое можно применять к переменным, методам, классам и блокам. В этом посте представлен обзор поведения переменных, методов, классов и блоков кода в Java, когда к ним применяется ключевое слово static. Давайте подробно обсудим каждый из них:

1. Статические переменные

  1. Статические переменные также известны как переменные класса.
  2. Когда статический ключевое слово применяется к переменной, это означает, что переменная принадлежит классу, а не экземпляру класса.
  3. В памяти есть только одна копия статической переменной, которая используется всеми экземплярами класса.
  4. Статические переменные инициализируются перед любой из переменных экземпляра.
  5. Статические переменные можно использовать, когда какое-то значение необходимо разделить между всеми объектами класса. Чтобы гарантировать, что значение никогда не изменится после его инициализации, объявите статическую переменную как final.
  6. Доступ к статической переменной можно получить напрямую, используя имя класса, без создания экземпляра класса, в котором они определены. Используйте обозначение >.> для доступа к статической переменной. В пределах одного класса к ним можно получить прямой доступ.
  7. Стандартный выходной поток System.out отличный пример статической переменной в Java. Здесь out объявляется статическим в System учебный класс.

Рассмотрим следующий код со статической переменной i определено в классе A . К нему можно получить прямой доступ по имени i внутри класса A и с A.i вне класса A .

Источник

Оцените статью