Trong lập trình hướng đối tượng, một biến thành viên (tiếng Anh: member variable), thỉnh thoảng còn được gọi là trường thành viên (member field) là một biến được kết hợp với một đối tượng cụ thể, và có thể truy xuất được đối với tất cả phương thức của nó (hàm thành viên). Trong ngôn ngữ dựa vào lớp, chúng được chia thành hai loại: nếu chỉ có một bản sao của biến được chia sẻ với tất cả thực thể của lớp, nó được gọi là biến lớp (class variable) hay biến thành viên tĩnh; còn nếu mỗi thực thể của lớp có bản sao riêng của biến, biến được gọi là biến thực thể (instance variable).[1]

Ví dụ sửa

C++ sửa

#include <iostream>
class Foo {
    int bar; // Member variable
  public:
    void setBar (const int newBar) { bar = newBar; }
};

int main () {
  Foo rect; // Local variable

  return 0;
}

Java sửa

class Program
{
    static void main(final String arguments[])
    {
    	// This is a local variable. Its lifespan
    	// is determined by lexical scope.
    	Foo foo;
    }
}

class Foo
{
    // This is a member variable - a new instance
    // of this variable will be created for each 
    // new instance of Foo.  The lifespan of this
    // variable is equal to the lifespan of "this"
    // instance of Foo
    int bar;
}

Xem thêm sửa

Tham khảo sửa

  1. ^ Richard G. Baldwin (10 tháng 3 năm 1999). “Q - What is a member variable?”. http://www.dickbaldwin.com/: Richard G Baldwin Programming Tutorials. Truy cập ngày 12 tháng 8 năm 2011. A member variable is a member of a class (class variable) or a member of an object instantiated from that class (instance variable). It must be declared within a class, but not within the body of a method of the class.