Modifiers in Java: static, final, abstract, synchronized, transient, volatile. Modifiers in Java: static, final, abstract, synchronized, transient, volatile Protected access modifiers protected


Which you add during initialization to change values. The Java language has a wide range of modifiers, the main ones being:

  • access modifiers;
  • class, method, variable, and thread modifiers used for non-access purposes.

To use a modifier in Java, you need to include its keyword in the definition of a class, method, or variable. The modifier must come before the rest of the statement, as shown in the following examples:

Public class className ( // ... ) private boolean myFlag; static final double weeks = 9.5; protected static final int BOXWIDTH = 42; public static void main(String arguments) ( // method body )

Access modifiers

Java provides a number of access modifiers to specify access levels for classes, variables, methods, and constructors. There are four accesses:

  • Visible in the package (this is the default and no modifier is required).
  • Visible only to the class (private).
  • Visible to everyone (public).
  • Visible to the package and all subclasses (protected).

Default access modifier - no keyword

Default access modifier- means that we do not explicitly declare an access modifier in Java for a class, field, method, etc.

A variable or method declared without an access control modifier is accessible to any other class in the same package. Fields in an interface are implicitly public, static, final, and methods in an interface are public by default.

Example

Variables and methods can be declared in Java without any modifiers, as shown in the following example:

String version = "1.5.1"; boolean processOrder() ( return true; )

Private access modifier

Modifier private- methods, variables and constructors that are declared private in Java can only be accessed within the declared class itself.

The private access modifier is the most restrictive access level. Class and interfaces cannot be private.

Variables declared private can be accessed outside the class if the public methods that receive them are present in the class (see example and explanation below).

Using the private modifier in Java is the main way to hide data.

Example

The following class uses private access control:

Public class Logger ( private String format; public String getFormat() ( return this.format; ) public void setFormat(String format) ( this.format = format; ) )

Here the variable format class Logger is private, so there is no way for other classes to get and set its value directly.

So to make this variable available to everyone, we defined two public methods: getFormat() which returns a value format, And setFormat(String), which sets its value.

public access modifier

public modifier- class, method, constructor, interface, etc. declared as public can be accessed from any other class. Therefore, fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java “universe”.

However, if we try to access a public class in another package, then the public class must be imported.

Thanks to class inheritance, in Java, all public methods and variables of a class are inherited by its subclasses.

Example

The following function uses public access control:

Public static void main(String arguments) ( // ... )

Method main() must be public. Otherwise, it cannot be called using the java interpreter to run the class.

Access modifier protected

Modifier protected- Variables, methods and constructors that are declared protected in a superclass can only be accessed by subclasses in another package or by any class in a package of the protected class.

The protected access modifier in Java cannot be applied to class and interfaces. Methods and fields can be declared protected, but methods and fields in an interface cannot be declared protected.

Protected access gives a subclass the ability to use a helper method or variable, preventing an unrelated class from trying to use it.

Example

The following parent class uses the protected access control so that its child class will override the method openSpeaker():

Class AudioPlayer ( protected boolean openSpeaker(Speaker sp) ( // implementation details ) ) class StreamingAudioPlayer ( boolean openSpeaker(Speaker sp) ( // implementation details ) )

Moreover, if we define a method openSpeaker() as protected, then it will not be accessible from any other class except AudioPlayer. If we define it as public, then it will become available to everyone. But our intention is to expose this method only to the subclass, that's why we used the protected modifier.

Access control and inheritance rules

The following rules in Java apply to inherited methods:

  • Methods declared public in the superclass must also be public in all subclasses.
  • Methods declared protected in the superclass must either be protected or public in subclasses; they cannot be private.
  • Methods declared private are not inherited by everyone, so there is no rule for them.

Class, method, variable, and thread modifiers used for non-access purposes

Java provides a number of modifiers not for access, but for implementing many other functionalities:

  • modifier static used to create class methods and variables;
  • modifier final used to complete the implementation of classes, methods and variables;
  • modifier abstract necessary for creating abstract classes and methods;
  • modifiers synchronized And volatile used in Java for threads.

Modifier static

Modifier static- used to create class methods and variables.

static variables

The static keyword is used to create variables that will exist independently of any instances created for the class. Only one copy of a static variable in Java exists, regardless of the number of instances of the class.

Static variables are also known as class variables. In Java, local variables cannot be declared static.

static methods

The static keyword is used to create methods that will exist independently of any instances created for the class.

In Java, static methods or static methods do not use any instance variables of any class object, they are defined. The static methods accept all the data from the parameters and some of these parameters are calculated without reference to the variables.

Class variables and methods can be accessed by using the class name followed by a period and the name of the variable or method.

Example

The static modifier in Java is used to create methods of classes and variables, as shown in the following example:

Public class InstanceCounter ( private static int numInstances = 0; protected static int getCount() ( return numInstances; ) private static void addInstance() ( numInstances++; ) InstanceCounter() ( InstanceCounter.addInstance(); ) public static void main(String arguments ) ( System.out.println("Starting from " + InstanceCounter.getCount() + " instance"); for (int i = 0; i

The following result will be obtained:

Starting from 0 instance 500 instances created

final modifier

final modifier- used to complete the implementation of classes, methods and variables.

Final variables

A final variable can only be initialized once. A reference variable declared as final can never be assigned to refer to another object.

However, the data inside the object can be changed. Thus, the state of an object can be changed, but not the reference.

With variables in Java, the final modifier is often used with static to make a class variable constant.

Example

public class Test( final int value = 10; // Below are examples of constant declarations: public static final int BOXWIDTH = 6; static final String TITLE = "Manager"; public void changeValue(){ value = 12; //будет получена ошибка } } !}

final methods

The final method cannot be overridden by any subclass. As mentioned earlier, in Java, the final modifier prevents a method from being modified by a subclass.

The main intention of making a method final would be that the contents of the method should not be changed side by side.

Example

A method declaration that uses the final modifier in a class declaration is shown in the following example:

Public class Test( public final void changeName())( // method body ) )

final class

The main purpose in Java of using a class declared as final is to prevent the class from being a subclass. If a class is marked as final, then no class can inherit any function from the final class.

Example

public final class Test ( // class body )

abstract modifier

abstract modifier- used to create abstract classes and methods.

Class abstract

An abstract class cannot instantiate. If a class is declared abstract, then its only purpose is to be extended.

A class cannot be both abstract and final, since a final class cannot be extended. If a class contains abstract methods, then it must be declared abstract. Otherwise, a compilation error will be generated.

The abstract class can contain both abstract methods and regular ones.

Example

abstract class Caravan( private double price; private String model; private String year; public abstract void goFast(); //abstract method public abstract void changeColor(); )

abstract method

An abstract method is a method declared with any implementation. The method body (implementation) is provided by the subclass. Abstract methods can never be final or strict.

Any class that extends an abstract class must implement all of the superclass's abstract methods, unless the subclass is an abstract class.

If a class in Java contains one or more abstract methods, then the class must be declared abstract. An abstract class is not required to contain abstract methods.

An abstract method ends with a semicolon. Example: public abstract sample();

Example

public abstract class SuperClass( abstract void m(); //abstract method ) class SubClass extends SuperClass( // implements abstract method void m())( ......... ) )

synchronized modifier

synchronized modifier

The synchronized keyword is used to indicate that a method can only be accessed by one thread at a time. In Java, the synchronized modifier can be applied with any of the four access level modifiers.

Example

public synchronized void showDetails() ( ....... )

Transient modifier

An instance variable marked transient tells the Java Virtual Machine (JVM) to skip a particular variable when serializing the object containing it.

This modifier is included in a statement that creates a variable of the variable's preceding class or data type.

Example

public transient int limit = 55; // will not be saved public int b; // will be saved

volatile modifier

volatile modifier- used in Java for threads.

In Java, the volatile modifier is used to let the JVM know that a thread accessing a variable should always merge its own copy of the variable with the master copy in memory.

Accessing a volatile variable synchronizes all cached copied variables in RAM. Volatile can only be applied to instance variables that are of type object or private. A volatile object reference can be null.

Example

public class MyRunnable implements Runnable( private volatile boolean active; public void run())( active = true; while (active)( // line 1 // some code here ) ) public void stop())( active = false; / / line 2 ) )

Typically, run() is called on one thread (when you first start using Runnable in Java) and stop() is called on another thread. If line 1 uses the cached active value, then the loop cannot stop until you set active to false on line 2.

In the next lesson, we will discuss the basic operators used in the Java language. This section will give you an overview of how you can use them during application development.

We will talk about modifiers: what modifiers are, scopes, modifiers for classes, fields, methods. I think it won't be boring.

Modifiers in Java are keywords that give a class, class field, or method certain properties.

To indicate the visibility of a class of its methods and fields, there are 4 access modifiers:

  • private class members are accessible only within the class;
  • package-private or default (default) class members are visible inside the package;
  • protected class members are available inside the package and in descendant classes;
  • public class members are available to everyone.

If you remember, at the end, when we had already imported the Cat class, we still had a compilation error.

The thing is that we have not specified any access modifiers to our fields and methods and they have a default property (class members are visible inside the package). To fix the compilation error for our code and finally run it, we need to make our constructor and methods public. Then they can be called from other packages.

You may begin to wonder: what is all this for? Why not make code visible from any package or class, but you need to restrict access? These questions will disappear on their own when the time comes to write complex and cumbersome projects. Now, when we write applications whose functionality is limited to one or two classes, there seems to be no point in limiting anything.

Imagine that you have a class that displays an object of a certain product. For example a car. The car may have a price. You have created a price field and many other fields, a bunch of methods that are responsible for functionality. Everything seems fine. Your class car is part of a huge project and everyone is happy. But let's say that someone accidentally or intentionally created an instance of the car class and set a negative price. Can a product have a negative price? This is a very primitive example and it is unlikely that this could happen in real life, but I think the idea is clear. Sometimes you need to give access not directly, but through certain methods. It may be that the code is responsible for the functionality of another code, and you do not want someone to change and edit part of yours. For this purpose there is an access restriction.

The access modifier for constructors, methods and fields can be anything. A class can only be either public or default, and there can only be one public class in one file.

Enough about access modifiers for now. In the article “Object Oriented Programming” we will talk about them in more detail, but now let’s talk about other modifiers of which, by the way, there are many.

Now comes the modifier static. It can be used before a method, field, and even a class when we want to declare a nested class. In Java, you can write classes inside other classes, and if the modifier before the class inside the class is static, then such a class is called nested, if another modifier is or default, then such a class is called internal. There will be a separate article about nested and inner classes, since everything is not so simple there.

The static modifier before a method or field indicates that it does not belong to an instance of that class. What does this mean for us? When we have declared a class field or method as static, it can be called without using an instance of the class. That is, instead of this construction: Cat cat = new Cat(); cat.method(), you can simply write Cat.method(). Provided that the method is declared as static. Static variables are the same for all class objects. They have one link.

    public class Modifiers (

    static int anotherStaticField = 5 ;

    public static void myStaticMethod() (

    someField = "My field" ;

    //nonStaticField = ""; compilation error

    //you can't use non-static fields

    //in static methods

    public void myNonStaticMethod() (

    anotherStaticField = 4 ; //static fields can be used

    //in non-static methods

    //main method also has a static modifier

    new Modificators() .myNonStaticMethod() ;

    Modificators.myStaticMethod(); //call static methods and fields

    //via Classname.method

Another important point to make about static modifiers is that static fields are initialized when the class is loaded. Often in various types of Java tests you can find the following code:

Question: what will be output to the console? You need to remember that the static block will be output first in any case. Next will be the default block. Next, look at the console screen:

The next modifier we'll look at will be final.

I think the word final speaks for itself. By using the final modifier, you say that fields cannot be changed, methods cannot be overridden, and classes cannot be inherited (there will be a separate article about inheritance). This modifier only applies to classes, methods and variables (also local variables).

We will talk about the final modifier to methods and classes in the OOP article.

Next will be modifiers that will not be very clear to beginners or those reading this series of articles from scratch. And although I won’t be able to explain everything to you yet (due to the fact that you don’t know the accompanying material), I still advise you to just familiarize yourself with them. When it comes time to use these modifiers, you will already understand most of the terms used below.

Modifier synchronized- indicates that the method can only be used by one thread at a time. Although this may not tell you anything, the usefulness of this modifier will be seen when we study multithreading.

Modifier transient— indicates that a certain field should be ignored during object serialization. As a rule, such fields store intermediate values.

Modifier volatile- used for multithreading. When a field with the volatile modifier will be used and changed by multiple threads, this modifier ensures that the field will be changed in turn and there will be no confusion with it.

Modifier native before declaring a method, indicates that the method is written in another programming language. Usually in C language.

Modifier strictfp— Ensures that operations on float and double numbers (floating point) are performed according to the IEEE 754 standard. Or, more simply, it guarantees that within the method, the results of calculations will be the same on all platforms.

I haven't talked about the modifier yet abstract. I’ll talk about it briefly, because without knowledge of the basics of object-oriented programming, I don’t see any point in talking about it.

A class that has the abstract modifier cannot create an instance. The only purpose for it is to be expanded. The abstract class can contain both abstract methods and regular ones.

We will talk more about the abstract modifier in the OOP article.

This is where we can finish the article about modifiers. Much has not been said about them. But this is due to the fact that we do not yet have the concepts of OOP. Over the course of several articles, we will expand the knowledge about modifiers and fill in the gaps.

Last update: 04/20/2018

All class members in Java - fields and methods - have access modifiers. In previous topics, we have already encountered the public modifier. Access modifiers allow you to set the permissible scope for class members, that is, the context in which a given variable or method can be used.

Java uses the following access modifiers:

    public : A public, public class or member of a class. Fields and methods declared with the public modifier are visible to other classes from the current package and from external packages.

    private : A private class or class member, the opposite of the public modifier. A private class or class member is accessible only from code in the same class.

    protected: such a class or class member is accessible from anywhere in the current class or package or in derived classes, even if they are in other packages

    Default modifier. The absence of a modifier for a class field or method implies that the default modifier is applied to it. Such fields or methods are visible to all classes in the current package.

Let's look at access modifiers using the following program as an example:

Public class Program( public static void main(String args) ( Person kate = new Person("Kate", 32, "Baker Street", "+12334567"); kate.displayName(); // normal, method public kate. displayAge(); // ok, the method has a default modifier kate.displayPhone(); // ok, method protected //kate.displayAddress(); // ! Error, method private System.out.println(kate.name) ; // ok, default modifier System.out.println(kate.address); // ok, modifier public System.out.println(kate.age); // ok, modifier protected //System.out.println( kate.phone); // ! Error, modifier private ) ) class Person( String name; protected int age; public String address; private String phone; public Person(String name, int age, String address, String phone)( this. name = name; this.age = age; this.address = address; this.phone = phone; ) public void displayName())( System.out.printf("Name: %s \n", name); ) void displayAge ()( System.out.printf("Age: %d \n", age); ) private void displayAddress())( System.out.printf("Address: %s \n", address); ) protected void displayPhone())( System.out.printf("Phone: %s \n", phone); ))

In this case, both classes are located in one package - the default package, so in the Program class we can use all the methods and variables of the Person class, which have the default modifier, public and protected. And fields and methods with the private modifier in the Program class will not be available.

If the Program class were located in another package, then only fields and methods with the public modifier would be available to it.

The access modifier must precede the rest of the variable or method definition.

Encapsulation

It would seem, why not declare all variables and methods with the public modifier so that they are available anywhere in the program, regardless of the package or class? Take for example the age field, which represents age. If another class has direct access to this field, then there is a possibility that during program operation it will be passed an incorrect value, for example, a negative number. Such data modification is not advisable. Or we want some data to be directly accessible so that we can display it on the console or simply find out its value. In this regard, it is recommended to restrict access to data as much as possible in order to protect it from unwanted access from the outside (both to get the value and to change it). The use of various modifiers ensures that the data is not distorted or changed inappropriately. Hiding data in this way within a scope is called encapsulation.

So, as a rule, instead of using fields directly, access methods are usually used. For example:

Public class Program( public static void main(String args) ( Person kate = new Person("Kate", 30); System.out.println(kate.getAge()); // 30 kate.setAge(33); System .out.println(kate.getAge()); // 33 kate.setAge(123450); System.out.println(kate.getAge()); // 33 ) ) class Person( private String name; private int age ; public Person(String name, int age)( this.name = name; this.age = age; ) public String getName())( return this.name; ) public void setName(String name)( this.name = name; ) public int getAge() ( return this.age; ) public void setAge(int age)( if(age > 0 && age< 110) this.age = age; } }

And then, instead of directly working with the name and age fields in the Person class, we'll work with methods that set and return the values ​​of these fields. Methods setName, setAge and the like are also called mutaters, since they change the values ​​of a field. And the methods getName, getAge and the like are called accessors, since with their help we get the value of the field.

Moreover, we can put additional logic into these methods. For example, in this case, when the age changes, a check is made to see how well the new value fits within the acceptable range.

First, let's look at access modifiers. There are only four of them:

  • private class members are only accessible within the class
  • package-private or default (default) class members are visible inside the package
  • protected class members are available inside the package and in descendant classes
  • public class members are available to everyone

During inheritance, it is possible to change access modifiers towards MORE visibility.

Constructors, methods and fields can have any access modifier, but with classes and their blocks everything is not so simple. A class can only be either public or default, and there can only be one public class in one file. A block can only have one modifier – default.

Modifiers static, abstract and final

Static

  • Applies to inner classes, methods, variables and logical blocks
  • Static variables are initialized when the class is loaded
  • Static variables are the same for all class objects (same reference)
  • Static methods only have access to static variables
  • Static methods and variables can be accessed through the class name
  • Static blocks are executed during class loading
  • Non-static methods cannot be overridden as static
  • Local variables cannot be declared as static
  • Abstract methods cannot be static
  • Static fields are not serialized (only when implementing the Serializable interface)
  • Only static class variables can be passed to a parameterized constructor called via super(//parameter//) or this(//parameter//)

Abstract

  • Applies only to methods and classes
  • Abstract methods do not have a method body
  • It is the opposite of final: a final class cannot be inherited, an abstract class must be inherited
  • A class must be declared abstract if:
  1. it contains at least one abstract method
  2. it does not provide implementation of inherited abstract methods
  3. it does not provide an implementation of the methods of the interface whose implementation it declared
  4. it is necessary to prohibit the creation of instances of the class

Final

  • Fields cannot be changed, methods are overridden
  • Classes cannot be inherited
  • This modifier only applies to classes, methods and variables (also local variables)
  • Method arguments marked as final are read-only; attempting to change them will result in a compilation error.
  • Final variables are not initialized by default; they must be explicitly assigned a value when declared or in the constructor, otherwise there will be a compilation error.
  • If a final variable contains a reference to an object, the object can be modified, but the variable will always refer to the same object
  • This is also true for arrays, because arrays are objects - the array can be changed, but the variable will always refer to the same array
  • If a class is declared final and abstract (mutually exclusive), a compilation error will occur
  • Since a final class cannot be inherited, its methods can never be overridden
Constructor cannot be static, abstract or final

Modifiers strictfp, transient, volatile, synchronized, native

Strictfp

  • Applies to methods and classes
  • Provides operations on float and double numbers (floating point) according to the IEEE 754 standard

Transient

  • Only applies to class level variables (local variables cannot be declared transient)
  • Transient variables may not be final or static.
  • Transient variables are not serialized

Volatile

  • Only used with variables
  • Can be used with static variables
  • Not used with final variables - The value of a variable declared as volatile, changed by one thread, is changed asynchronously for other threads
  • Used in multi-threaded applications

Synchronized

  • Applies only to methods or parts of methods
  • Used to control access to important parts of code in multi-threaded programs

Native

  • Only used for methods
  • Indicates that the method is written in a different programming language
  • Classes in Java use many native methods to improve performance and access to hardware
  • You can pass/return Java objects from native methods
  • The method signature must end with “;”, curly braces will cause a compilation error

Features in interfaces

  • Methods are always public and abstract, even if it is not declared
  • Methods cannot be static, final, strictfp, native, private, protected
  • Variables are only public static final, even if it is not declared
  • Variables cannot be strictfp, native, private, protected
  • Can only extend another interface, but not implement an interface or class.

Let's put all the modifiers together:

Class

Inner class

Variable

Method

Constructor

Logic block

public

Yes

Yes

Yes

Yes

Yes

No

protected

No

Yes (except local and anonymous classes)

Yes

Yes

Yes

No

default

Yes

Yes

Yes

Yes

Yes

private

No

Yes (except local and anonymous classes)

Yes

Yes

Yes

No

final

Yes

Yes (and for local variable)

Yes

No

No

abstract

Yes

Yes (except anonymous classes)

No

Yes

No

No

static

No

Yes (except local and anonymous classes)

Yes

Yes

No

Yes

native

No

No

No

Yes

No

No

transient

No

No

Yes

No

No

No

synchronized

No

No

No

Yes

No

Yes (only as part of the method)

volatile

No

No

Yes

No

No

No

strictfp

Yes

Yes

No

Yes

No

No

It is possible to control which parts of the program can access class members. Access control helps prevent abuse. It is not always desirable to have access to a separate class variable or method that should only work within the class itself.

The access method is determined access modifier, which is added when declared. There are four in total:

  • private
  • public (open)
  • protected
  • default access when no modifier is present

Examples of declaring modifiers (it should always come first):

Public int i; private double j, k; private int createMethod(int a) (...); public class Cat()

As you can see, the modifier is applicable to a variable, method, class.

public

When using a keyword public you are telling that the class member declaration that follows is accessible to everyone from any other code in your project.

Suppose the class is declared as public, and it has two methods. One private, second - public. You will have access to the class and second method, but not to the first one, despite the fact that the class itself is public.

private

Keyword private means that access to a member of a class is not granted to anyone other than methods of that class. Other classes in the same package cannot access private members either.

All auxiliary class methods should be declared as private to prevent them from being accidentally called in a batch. The same applies to private fields inside a class.

protected

Keyword protected is associated with the concept of inheritance, in which new members are added to an already existing class (base) while the original implementation remains unchanged. You can also change the behavior of existing class members. To create a new class based on an existing one, use the keyword extends.

If you create a new package and inherit from a class in another package, the new class only has access to the public members of the original package. Sometimes the creator of a base class needs to grant access to a particular method to derived classes, but keep it private from everyone else. In these cases the keyword is used protected. Specifier protected also provides access within the package, i.e. members with this specifier are available to other classes from the same package.

By default, if there is no modifier, a class member is considered public within its own package, but not accessible to code outside that package. If all of your project's classes are in the same package, then essentially a variable without a modifier is public ( public).

Consider a fictional class SillySensor

Public class SillySensor ( private int sensorData; public SillySensor() ( sensorData = 0; ) private void calibrate(int iSeed) ( // code for calibration ) protected void seedCalibration(int iSeed) ( calibrate(iSeed); ) public int getSensorData( ) ( // Check sensor here return sensorData; ) )

The class is declared as public and is available in other classes. The class has a variable sensorData, which is available only in its class (private). The constructor is available in other classes ( public). Method calibrate() only works inside a class ( private). Method seedCalibration() available in its own class or subclass ( protected). Method getSensorData() available in other classes ( public).







2024 gtavrl.ru.