The third column indicates whether subclasses of the class declared outside this package have access to the member.;

Java成员变量、局部变量、静态变量、成员方法、全局方法等概念的区别 - S1amDuncan的博客 - CSDN博客 https://blog.csdn.net/s1amduncan/article/details/52089944

      在Java中,一个类体由2部分构成:
一部分是变量的定义;
一部分是方法的定义(一个类中可以有多个方法)  

Java中的变量可以分为成员变量,全局变量

成员变量和局部变量的区别

       成员变量:(类似于C中的全局变量的概念,所以也可以说是全局变量)

          ①成员变量定义在类中,在整个类中都可以被访问。

          ②成员变量随着对象的建立而建立,随着对象的消失而消失,存在于对象所在的堆内存中。

          ③成员变量有默认初始化值。

      局部变量:

          ①局部变量只定义在局部范围内,如:函数内,语句内等,只在所属的区域有效。

          ②局部变量存在于栈内存中,作用的范围结束,变量空间会自动释放。

          ③局部变量没有默认初始化值 

      在使用变量时需要遵循的原则为:就近原则

      首先在局部范围找,有就使用;接着在成员位置找。

静态变量(也叫做类变量,类属性)

      由static修饰的变量称为静态变量,其实质上就是一个全局变量。如果某个内容是被所有对象所共享,那么该内容就应该用静态修饰;没有被静态修饰的内容,其实是属于对象的特殊描述。

成员变量和静态变量的区别

      1、两个变量的生命周期不同

            成员变量随着对象的创建而存在,随着对象被回收而释放。

            静态变量随着类的加载而存在,随着类的消失而消失。

      2、调用方式不同

            成员变量只能被对象调用。

            静态变量可以被对象调用,还可以被类名调用。

      3、别名不同

            成员变量也称为实例变量。

            静态变量也称为类变量。

      4、数据存储位置不同

            成员变量存储在堆内存的对象中,所以也叫对象的特有数据。

            静态变量数据存储在方法区(共享数据区)的静态区,所以也叫对象的共享数据。

列表对比:

       成员变量、局部变量、静态变量的区别 

 

成员变量

局部变量

静态变量

定义位置

 在类中,方法外

方法中,或者方法的形式参数

在类中,方法外

初始化值

有默认初始化值

,先定义,赋值后才能使用

有默认初始化值

调用方式

对象调用

---

对象调用,类名调用

存储位置

堆中

栈中

方法区

生命周期

与对象共存亡

与方法共存亡

与类共存亡

别名

实例变量

---

类变量


  1.  
    class Demo{
  2.  
    int x;// 非静态成员变量,又称为属性,对该类不同的对象来说,属性是不同的
  3.  
    static int y;// 静态成员变量,一个类中只有一个该变量,该类不同的对象共享同一个静态成员变量
  4.  
    public static void main(String[] args){
  5.  
    int m = 0;// 局部变量,是方法内部定义的变量,只在方法内部可见,在该方法结束后,由垃圾回收器自动回收
  6.  
    }
  7.  
    }




Java中的方法可以分为成员方法,全局方法,构造方法

  1.  
    public class Test {
  2.  
    private int age; //这是成员变量
  3.  
    public Test(int age) { //这是构造方法
  4.  
    this.age = age;
  5.  
    }
  6.  
    public void setAge(int age) { //这是成员方法
  7.  
    this.age = age;
  8.  
    }
  9.  
    public static int getAge() { //这是全局方法,加了static关键字,成员方法就变成了全局方法
  10.  
    return this.age;
  11.  
    }
  12.  
    }
成员方法必须用类的实例化对象进行访问,而全局方法是直接可以用类名.方法名来访问的,构造方法则是实例化对象时进行初始化的
 

Controlling Access to Members of a Class (The Java™ Tutorials > Learning the Java Language > Classes and Objects) https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

Access level modifiers determine whether other classes can use a particular field or invoke a particular method. There are two levels of access control:

  • At the top level—public, or package-private (no explicit modifier).
  • At the member level—publicprivateprotected, or package-private (no explicit modifier).

A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes — you will learn about them in a later lesson.)

At the member level, you can also use the public modifier or no modifier (package-private) just as with top-level classes, and with the same meaning. For members, there are two additional access modifiers: private and protected. The private modifier specifies that the member can only be accessed in its own class. The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

The following table shows the access to members permitted by each modifier.

Access Levels
ModifierClassPackageSubclassWorld
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

The first data column indicates whether the class itself has access to the member defined by the access level. As you can see, a class always has access to its own members. The second column indicates whether classes in the same package as the class (regardless of their parentage) have access to the member. The third column indicates whether subclasses of the class declared outside this package have access to the member. The fourth column indicates whether all classes have access to the member.

Access levels affect you in two ways. First, when you use classes that come from another source, such as the classes in the Java platform, access levels determine which members of those classes your own classes can use. Second, when you write a class, you need to decide what access level every member variable and every method in your class should have.

Let's look at a collection of classes and see how access levels affect visibility. The following figure shows the four classes in this example and how they are related.

 

Classes and Packages of the Example Used to Illustrate Access Levels

The following table shows where the members of the Alpha class are visible for each of the access modifiers that can be applied to them.

The following table shows where the members of the Alpha class are visible for each of the access modifiers that can be applied to them.

Visibility
ModifierAlphaBetaAlphasubGamma
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

Tips on Choosing an Access Level: 

If other programmers use your class, you want to ensure that errors from misuse cannot happen. Access levels can help you do this.

  • Use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to.
  • Avoid public fields except for constants. (Many of the examples in the tutorial use public fields. This may help to illustrate some points concisely, but is not recommended for production code.) Public fields tend to link you to a particular implementation and limit your flexibility in changing your code.

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 cadencegear, 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:

public class Bicycle {
        
    private int cadence;
    private int gear;
    private int speed;
        
    // add an instance variable for the object ID
    private int id;
    
    // add a class variable for the
    // number of Bicycle objects instantiated
    private static int numberOfBicycles = 0;
        ...
}

Class variables are referenced by the class name itself, as in

Bicycle.numberOfBicycles

This makes it clear that they are class variables.


Note: You can also refer to static fields with an object reference like
myBike.numberOfBicycles
but this is discouraged because it does not make 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

ClassName.methodName(args)

Note: You can also refer to static methods with an object reference like
instanceName.methodName(args)
but this is discouraged because it does not make it clear that they are class methods.

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() {
    return numberOfBicycles;
}

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 directly—they 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;

        id = ++numberOfBicycles;
    }

    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;
    }
}
原文地址:https://www.cnblogs.com/rsapaper/p/10195863.html