Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Modifiers

Java Modifiers

The Java language provides many modifiers, mainly divided into the following two categories:

Modifiers are used to define classes, methods, or variables, and are usually placed at the front of a statement. We illustrate this with the following example:

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 control modifiers

In Java, access modifiers can be used to protect access to classes, variables, methods, and constructors. Java supports 4 different access levels.

We can illustrate the access permissions through the following table:

Modifiers Current class Same package Subclasses (same package) Subclasses (different package) Other packages
public Y Y Y Y Y
protected Y Y Y Y/N (Description) N
default Y Y Y N N
private Y N N N N

Default access modifier - no keyword used

If no access modifier is specified in the definition of a class, variable, method, or constructor, they default to the default access modifier.

The access level of the default access modifier is package-level, meaning it can only be accessed by other classes in the same package.

As shown in the following example, variables and methods can be declared without any modifier.

Example

//

MyClass.java

class

MyClass

{

//

Default access modifier

int

x

=

10

;

//

Default access modifier

void

display

(

)

{

//

Default access modifier

System

.

out

.

println

(

"

Value of x is:

"

x

)

;

}

}

//

MyOtherClass.java

class

MyOtherClass

{

public

static

void

main

(

String

[

]

args

)

{

MyClass

obj

=

new

MyClass

(

)

;

obj

.

display

(

)

;

//

Access the default-access-modifier variables and methods in MyClass

}

}

In the above example, the MyClass class and its member variable x and method display() are all defined with the default access modifier. The MyOtherClass class is in the same package, so it can access the MyClass class and its member variables and methods.

Private access modifier - private

The private access modifier is the most restrictive access level, so those declared as private methods, variables, and constructors can only be accessed by the class they belong to, and classes and interfaces cannot be declared as private.

Variables declared with private access can only be accessed by external classes through public getter methods in the class.

The private access modifier is mainly used to hide the implementation details of a class and protect its data.

The following class uses the private access modifier:

public

class

Logger

{

private

String

format

;

public

String

getFormat

(

)

{

return

this

.

format

;

}

public

void

setFormat

(

String

format

)

{

this

.

format

=

format

;

}

}

In the example, the format variable in the Logger class is a private variable, so other classes cannot directly get or set its value. To allow other classes to manipulate this variable, two public methods are defined: getFormat() (returns the value of format) and setFormat(String) (sets the value of format)

Public access modifier - public

Classes, methods, constructors, and interfaces declared as public can be accessed by any other class.

If several mutually accessible public classes are distributed across different packages, you need to import the packages containing the corresponding public classes. Due to class inheritance, all public methods and variables of a class can be inherited by its subclasses.

The following function uses public access control:

public

static

void

main

(

String

[

]

arguments

)

{

//

...

}

The main() method of a Java program must be declared public; otherwise, the Java interpreter will not be able to run the class.

Protected access modifier - protected

protected needs to be analyzed and explained from the following two points:

protected can modify data members, constructors, and method members,but cannot modify a class (except inner classes).

The member variables and member methods of an interface cannot be declared protected. You can see the illustration below:

Subclasses can access methods and variables declared with the protected modifier, which protects unrelated classes from using these methods and variables.

The following parent class uses the protected access modifier, and the subclass overrides the parent class's openSpeaker() method.

class

AudioPlayer

{

protected

boolean

openSpeaker

(

Speaker

sp

)

{

//

Implementation details

}

}

class

StreamingAudioPlayer

extends

AudioPlayer

{

protected

boolean

openSpeaker

(

Speaker

sp

)

{

//

Implementation details

}

}

If the openSpeaker() method is declared private, then no class other than AudioPlayer can access it.

If openSpeaker() is declared public, then all classes can access the method.

If we only want the method to be visible to subclasses of its class, we declare it protected.

protected is the most difficult Java class member access modifier to understand; for more details, please see Detailed explanation of the Java protected keyword.

Access control and inheritance

Please note the following method inheritance rules:


Non-access modifiers

To implement some other functionality, Java also provides many non-access modifiers.

The static modifier is used to modify class methods and class variables.

The final modifier is used to modify classes, methods, and variables. A class modified by final cannot be inherited, a method modified by final cannot be redefined by a subclass, and a variable modified by final is a constant that cannot be modified.

The abstract modifier is used to create abstract classes and abstract methods.

The synchronized and volatile modifiers are mainly used in thread programming.

static modifier

Access to class variables and methods can be done directly using classname.variablename and classname.methodname .

As shown in the following example, the static modifier is used to create class methods and class variables.

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 with

"

InstanceCounter

.

getCount

(

)

"

instances

"

)

;

for

(

int

i

=

0

;

i

<

500

; ++

i

)

{

new

InstanceCounter

(

)

;

}

System

.

out

.

println

(

"

Created

"

InstanceCounter

.

getCount

(

)

"

instances

"

)

;

}

}

The result of running the above example is as follows:


Starting with 0 instances
Created 500 instances

final modifier

final variables:

final means "last, final". Once a variable is assigned, it cannot be reassigned. An instance variable modified by final must be explicitly assigned an initial value.

The final modifier is usually used together with the static modifier to create class constants.

Example

public

class

Test

{

final

int

value

=

10

;

//

The following is an example of declaring a constant

public

static

final

int

BOXWIDTH

=

6

;

static

final

String

TITLE

=

"

Manager

"

;

public

void

changeValue

(

)

{

value

=

12

;

//

Will output an error

}

}

final method

A final method in the parent class can be inherited by subclasses but cannot be overridden by them.

The main purpose of declaring a final method is to prevent its content from being modified.

As shown below, declare a method using the final modifier.

public

class

Test

{

public

final

void

changeName

(

)

{

//

Method body

}

}

final class

A final class cannot be inherited; no class can inherit any characteristics of a final class.

Example

public

final

class

Test

{

//

Class body

}

abstract modifier

Abstract class:

An abstract class cannot be used to instantiate objects; the only purpose of declaring an abstract class is to extend it in the future.

A class cannot be modified by both abstract and final. If a class contains abstract methods, then the class must be declared as an abstract class; otherwise a compilation error will occur.

An abstract class can contain both abstract and non-abstract methods.

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 without any implementation; its concrete implementation is provided by the subclass.

An abstract method cannot be declared as final or static.

Any subclass that inherits an abstract class must implement all abstract methods of the parent class, unless the subclass is also abstract.

If a class contains several abstract methods, then the class must be declared as abstract. An abstract class may contain no abstract methods.

The declaration of an abstract method ends with a semicolon, for example:public abstract sample();.

Example

public

abstract

class

SuperClass

{

abstract

void

m

(

)

;

//

Abstract method

}

class

SubClass

extends

SuperClass

{

//

Implement the abstract method

void

m

(

)

{

.........

}

}

synchronized modifier

A method declared with the synchronized keyword can only be accessed by one thread at a time. The synchronized modifier can be applied to all four access modifiers.

Example

public

synchronized

void

showDetails

(

)

{

.......

}

transient modifier

When a serialized object contains an instance variable modified by transient, the Java Virtual Machine (JVM) skips that particular variable.

This modifier is included in the statement that defines the variable and is used to preprocess the data types of classes and variables.

Example

public

transient

int

limit

=

55

;

//

Will not be persisted

public

int

b

;

//

Persistence

volatile modifier

A member variable modified by volatile forces a re-read of its value from shared memory every time it is accessed by a thread. Moreover, when the member variable changes, it forces the thread to write the changed value back to shared memory. Thus, at any moment, two different threads always see the same value of a member variable.

A volatile object reference may be null.

Example

public

class

MyRunnable

implements

Runnable

{

private

volatile

boolean

active

;

public

void

run

(

)

{

active

=

true

;

while

(

active

)

//

First line

{

//

Code

}

}

public

void

stop

(

)

{

active

=

false

;

//

Second line

}

}

Normally, one thread calls the run() method (in the thread started by Runnable), and another thread calls the stop() method. If First line the active value in the buffer of is used, then in Second line , the loop will not stop when the active value is false.

But in the code above we used volatile to modify active, so the loop will stop.