Home >Java >javaTutorial >[java tutorial] Java modifiers

[java tutorial] Java modifiers

黄舟
黄舟Original
2016-12-26 11:31:071307browse

Java modifiers

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

Access modifiers

Non-access modifiers

* The &* modifier is used to define classes, methods or variables, and is usually placed at the front of the statement. We use the following example to illustrate:

public class className {
   // ...
}
private boolean myFlag;
static final double weeks = 9.5;
protected static final int BOXWIDTH = 42;
public static void main(String[] arguments) {
   // 方法体
}

Access control modifiers

In Java, you can use access control modifiers to protect access to classes, variables, methods and constructors. Java supports 4 different access rights.

The default, also called default, is visible within the same package and does not use any modifiers.

Private, specified with the private modifier, visible within the same class.

Common, specified with the public modifier, visible to all classes.

Protected, specified with the protected modifier, visible to classes and all subclasses in the same package.

Default access modifier - do not use any keywords

Variables and methods declared using the default access modifier are visible to classes in the same package. The variables in the interface are implicitly declared as public static final, and the access rights of the methods in the interface are public by default.

Example:

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

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

Private access modifier-private

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

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

Private access modifier is mainly used to hide the implementation details of the class and protect the data of the class.

The following classes use 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 instance, the format variable in the Logger class is a private variable, so other classes cannot directly get and set the value of the variable. In order to enable other classes to operate 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 public classes that access each other are distributed in different packages, you need to import the package where the corresponding public class is located. Due to class inheritance, all public methods and variables of a class can be inherited by its subclasses.

The following functions use public access control:

public static void main(String[] arguments) {
   // ...
}

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

Protected access modifier-protected

Variables, methods and constructors declared as protected can be accessed by any other class in the same package, or by classes in different packages subclass access. The

Protected access modifier cannot modify classes and interfaces. Methods and member variables can be declared protected, but member variables and member methods of interfaces cannot be declared protected.

Subclasses can access the methods and variables declared by the Protected modifier, thus protecting unrelated classes from using these methods and variables.

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

class AudioPlayer {
   protected boolean openSpeaker(Speaker sp) {
      // 实现细节
   }
}

class StreamingAudioPlayer {
   boolean openSpeaker(Speaker sp) {
      // 实现细节
   }
}

如果把openSpeaker()方法声明为private,那么除了AudioPlayer之外的类将不能访问该方法。如果把openSpeaker()声明为public,那么所有的类都能够访问该方法。如果我们只想让该方法对其所在类的子类可见,则将该方法声明为protected。

访问控制和继承

请注意以下方法继承的规则:

父类中声明为public的方法在子类中也必须为public。

父类中声明为protected的方法在子类中要么声明为protected,要么声明为public。不能声明为private。

父类中默认修饰符声明的方法,能够在子类中声明为private。

父类中声明为private的方法,不能够被继承。

非访问修饰符

为了实现一些其他的功能,Java也提供了许多非访问修饰符。

static修饰符,用来创建类方法和类变量。

Final修饰符,用来修饰类、方法和变量,final修饰的类不能够被继承,修饰的方法不能被继承类重新定义,修饰的变量为常量,是不可修改的。

Abstract修饰符,用来创建抽象类和抽象方法。

Synchronized和volatile修饰符,主要用于线程的编程。

Static修饰符

静态变量:

Static关键字用来声明独立于对象的静态变量,无论一个类实例化多少对象,它的静态变量只有一份拷贝。 静态变量也被成为类变量。局部变量能被声明为static变量。

静态方法:

Static关键字用来声明独立于对象的静态方法。静态方法不能使用类的非静态变量。静态方法从参数列表得到数据,然后计算这些数据。

对类变量和方法的访问可以直接使用classname.variablename和classname.methodname的方式访问。

如下例所示,static修饰符用来创建类方法和类变量。

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");
   }
}

以上实例运行编辑结果如下:

Started with 0 instances
Created 500 instances

Final修饰符

Final变量:

Final变量能被显式地初始化并且只能初始化一次。被声明为final的对象的引用不能指向不同的对象。但是final对象里的数据可以被改变。也就是说final对象的引用不能改变,但是里面的值可以改变。

Final修饰符通常和static修饰符一起使用来创建类常量。

实例:

public class Test{
  final int value = 10;
  // 下面是声明常量的实例
  public static final int BOXWIDTH = 6;
  static final String TITLE = "Manager";

  public void changeValue(){
     value = 12; //将输出一个错误
  }
}

Final方法

类中的Final方法可以被子类继承,但是不能被子类修改。

声明final方法的主要目的是防止该方法的内容被修改。

如下所示,使用final修饰符声明方法。

public class Test{
    public final void changeName(){
       // 方法体
    }
}

Final类

Final类不能被继承,没有类能够继承final类的任何特性。

实例:

public final class Test {
   // 类体
}

Abstract修饰符

抽象类:

抽象类不能用来实例化对象,声明抽象类的唯一目的是为了将来对该类进行扩充。

一个类不能同时被abstract和final修饰。如果一个类包含抽象方法,那么该类一定要声明为抽象类,否则将出现编译错误。

抽象类可以包含抽象方法和非抽象方法。

实例:

abstract class Caravan{
   private double price;
   private String model;
   private String year;
   public abstract void goFast(); //抽象方法
   public abstract void changeColor();
}

抽象方法

抽象方法是一种没有任何实现的方法,该方法的的具体实现由子类提供。抽象方法不能被声明成final和strict。

任何继承抽象类的子类必须实现父类的所有抽象方法,除非该子类也是抽象类。

如果一个类包含若干个抽象方法,那么该类必须声明为抽象类。抽象类可以不包含抽象方法。

抽象方法的声明以分号结尾,例如:public abstract sample();

实例:

public abstract class SuperClass{
    abstract void m(); //抽象方法
}
 
class SubClass extends SuperClass{
     //实现抽象方法
      void m(){
          .........
      }
}

Synchronized修饰符

Synchronized关键字声明的方法同一时间只能被一个线程访问。Synchronized修饰符可以应用于四个访问修饰符。

实例:

public synchronized void showDetails(){
.......
}

Transient修饰符

序列化的对象包含被transient修饰的实例变量时,java虚拟机(JVM)跳过该特定的变量。

该修饰符包含在定义变量的语句中,用来预处理类和变量的数据类型。

实例:

public transient int limit = 55;   // will not persist
public int b; // will persist

volatile修饰符

Volatile修饰的成员变量在每次被线程访问时,都强迫从共享内存中重读该成员变量的值。而且,当成员变量发生变化时,强迫线程将变化值回写到共享内存。这样在任何时刻,两个不同的线程总是看到某个成员变量的同一个值。一个volatile对象引用可能是null。

实例:

public class MyRunnable implements Runnable
{
    private volatile boolean active;
    public void run()
    {
        active = true;
        while (active) // line 1
        {
            // 代码
        }
    }
    public void stop()
    {
        active = false; // line 2
    }
}

一般地,在一个线程中调用run()方法,在另一个线程中调用stop()方法。如果line 1中的active位于缓冲区的值被使用,那么当把line 2中的active设置成false时,循环也不会停止。

 以上就是【java教程】Java修饰符的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn