热门问题
时间线
聊天
视角

实例变量

来自维基百科,自由的百科全书

Remove ads

以基于类础面向对象编程里,实例变量('instance variable)是定义在类别里的变量成员变量),类别里每一个初始化的物件都有一个此变量的实例,且各物件的实例变量是互相独立的[1][2]。实例变量类似类变量[3],但实例变量不是静态变量。在C++或Java语言中,实例变量是在类别中宣告,但是是在构造器方法以外的区域定义。实例变量是在物件初始化时就创建,类别中的所有构造器、方法或块都可以存取实例变量。也可以对实例变量加上存取修饰符英语Access modifiers

实例变量不是类变量[4],不过两者有相似之处。两者都是类别的属性(或性质、区段、资料元素)。同一类别不同物件的实例变量可能有不同的值,但同一个类别的类变量只会有一个,不同物件的类变量会共享。。“类别”和“实例”的差异也可以用在方法(成员函数)上,类别可以有实例方法(instance method),也可以有类方法。

实例变量会存储在存储器中,生命周期和其所属物件的生命周期相同[5]

实例变量是物件的属性。所有物件都会依其定义,有其自身的实例变量。物件可以更改其实例变量,不会影响其他物件的实例变量。一个物件可以同时有实例变量和类变量。

物件的所有方法都可以使用实例变量,只有类方法例外。若符合其存取权限,也可以直接设置实例变量[6]

Remove ads

示例

已隐藏部分未翻译内容,欢迎参与翻译

C++

struct Request {

    static int count1; // variable name is not important
    int number;

    Request() {
        number = count1; // modifies the instance variable "this->number"
        ++count1; // modifies the class variable "Request::count1"
    }

};

int Request::count1 = 0;

In this C++ example, the instance variable Request::number is a copy of the class variable Request::count1 where each instance constructed is assigned a sequential value of count1 before it is incremented. Since number is an instance variable, each Request object contains its own distinct value; in contrast, there is only one object Request::count1 available to all class instances with the same value.

Java

//Example.java

class Example {
    public int x = 0;
    
    public void setX(int newValue) {
        this.x = newValue;
    }
}

//Main.java

class Main {
    public static void main(String[] args) {
        Example example1 = new Example();
        Example example2 = new Example();
        
        //We can set the value of x by itself, as the variable is public
        example1.x = 10;
        
        assert example1.x == 10;
        assert example2.x ==  0;
        
        //As setX is an instance method, it can also access the variable
        example2.setX(-10);
        
        assert example1.x ==  10;
        assert example2.x == -10;
    }
}

In this Java example, we can see how instance variables can be modified in one instance without affecting another.

Python

class Dog:
    def __init__(self, breed):
        self.breed = breed # instance variable

# dog_1 is an object
# which is also an instance of the Dog class
dog_1 = Dog("Border Collie")
In the above Python code, the instance variable is created when an argument is parsed into the instance, with the specification of the breed positional argument.
Remove ads

参考资料

Loading related searches...

Wikiwand - on

Seamless Wikipedia browsing. On steroids.

Remove ads