Top Ad unit 728 × 90

Welcome !!! To The World of Programming

OOPS FEATURES

Oops

Instance Variables and Class Variables

Non-Static and Static  Fields in a Class

Instance (Non-Static) variables are unique to each instance (object) of a class. It represents the specific attributes of the objects. Class (Static) variables are shared among all instances of a class. It represents properties or values common to the entire class.

Instance Class  Variables


Instance Variables:

  • In object-oriented language, it is known as "member variables" or "instance fields."

  • Instance or an Object of a class (i.e., each object created from the class) has its own separate copy of fields or instance variables.

  • An instance variable represents the attributes or properties of objects created from the class (i.e. information of the required of the Entity).
  • Instance variables are typically declared within the class but outside of any methods.

  • Instance variables are accessed using object references.


Class Variables:

  • It is also known as "Static Variables" or "Class Fields."

  • Class variables are shared among all instances (objects) of a class.

  • It is only one copy of a class variable that is shared across all instances of the class.

  • It is typically used for values or properties that are common to all instances of the class.

  • Class variables are declared using the static or shared keyword within the class.


Scenario:

In object-oriented programming (OOP), an "Entity" is a very broad term. It generally refers to a real-world object, concept, or thing. It is modelled as an class in the software. In OOP, entities are modelled as a class. The objects of the class represent instances of this entity.

A real-world entity say Student. To model or use the Entity Student in a software, It is defined as a class ( user-defined data type). The information required of the Student are Roll-Number, Name and branch of Engineering (assume Computer Engineering) in which admission taken. The information required of an Entity becomes data-members or fields of the class, The Student class in Java can be defined as follows:



  class Student {
  //Instance fields or Non-Static fields 
  //seperate copy or memory is allocated when object or instance of class is created   
  private int rollNo;
  private String name;
  private String branch;
  }

Now just imagined , 60 admissions in Computer Engineering branch then to store and maintain data of 60 students, 60 objects of the Student class is to be created. Memory is allocated for each of  the fields of the class. The problem with this approach is that 60 times the Computer Engineering will be stored, although branch is common to all the students. It is wastage of memory. There is no point in storing the same data again and again. Here comes need of Class Variables of Static Fields.  The Class variable in Java is declared with the Keyword "Static" as shown in code below:

class Student {
  //Instance fields or Non-Static fields 
  //separate copy or memory is allocated when object or instance of class is created
  private int rollNo;
  private String name;
    //Class Variable or Static field
    //Only a Single copy of Memory is allocated
   private static String branch;
   }
The following figure demonstrate the concept of Instance and Class Variables of Fields in the class in object-oriented programming. 

instance-variable
The conclusion is to store common data about all the instances or an objects of the class. Memory will be allocated for static fields or class variables only once. However separate memory for each of the instance fields will be allocated for each of the object or an instances of the  class. Example - One classroom and many students in that class.

One of the significant feature of OOPS is Data Encapsulation. The data-members or fields are declared with the private access specifier to achieve Data hiding or data Encapsulation. The private data is only accessible to the member-functions or methods of the class. In other words, the public members-variables or instance fields are accessible directly outside the class whereas the private member-variables or instance fields are not accessible outside the class.


class Test {
    private:
      int a;
    public:
      int b;
 };
 
 int main() {
   //Object created  of Test class
   Test test;
   //test.a = 10; Not accessible as it is private
      test.b = 20; //Accessible as it is public
  return 0;
 }
 

Getters and Setters in OOPS:

The private data-members or fields is not accessible outside the class. The getters and setters are actually member-functions or methods to get or retrieve and set or assign the value to the fields of the class. 
  • Getter: A method that allows  to access or get or retrieve an attribute in a given class.
  • Setter: A method that allows  to set or mutate or assign the value of an attribute in a class.
The following example demonstrate the use of the Getter and the Setter method of the class.


  class Test {
    private:
      int a;
    public:
      int b;
      //Getter
      int getA() {
          return a;
      }
      //Setter
      void setA(int a) {
          this->a = a;
      }
 };
 
 int main() {
   //Object created  of Test class
   Test test;
   //test.a = 10; Not accessible as it is private
     test.b = 20; //Accessible as it is public
     test.setA(10);
     std::cout<<"a = "<<a;
     return 0;
    }
 
 

Furthermore, Let's explore the usage of instance and class variables in different Object-Oriented Languages.

 Instance Variables and Class Variables in C++:

In C++, the fields of the class is termed as an instant variables and memory is allocated for each field when an object is created. The class variables in C++ is declared with the static keyword.  It can be declared either in the private or public section. However its type and scope must be defined outside the class. It is necessary because memory allocated to the static data-member separately and not as part of the object or instance of a class.

class Test {
      private:
           static int count;
};
//Required
int Test::count;

The following code demonstrates the concept of instance and class variables in C++. It also shows that how getters and setters are used to get and set the values of the fields of the class.



using namespace std;

class Student{
 private:
	int rollNo;
	string name;
	static string branch;

 public:
 	Student(){
	 }
	//Getters 
 	int getRollNo(){
 		return this->rollNo;
	 }
	 //Setters
	void setRollNo(int rollNo){
		this->rollNo = rollNo;
	}
	
	string getName(){
 		return this->name;
	 }
	void setName(string name){
		this->name = name;
	}
	static string getBranch(){
 		return branch;
	 }
	static void setBranch(string Vbranch){
		branch = Vbranch;
	}
	
};

string Student::branch="";
int main(){
 //Create Objects
 Student s1;
 s1.setRollNo(101);
 s1.setName("Joe");
 Student::setBranch("Computer Engineering");
 cout<<"Branch: "<<student::getbranch();
 std::cout<<"Roll No. : "<<s1.getRollNo()<<"Name : "<<s1.getName()<<endl;
 Student s2;
 s2.setRollNo(102);
 s2.setName("James");
 std::cout<<"Roll No. : "<<s2.getRollNo()<<"Name : "<<s2.getName()<<endl;
 }
 


Instance Variables and Class Variables in Java:

In Java, the fields of the class is termed as an instant variables and memory is allocated for each field when an object is created. The class variables in Java is declared with the static keyword. In Java, accessor method is used to access the value of the instance variable and mutator method is used to assign the value to the instance variable 
The same example is implemented in Java as follows:



public class Student {
	private int rollNo;
	private String name;
	private static String branch;
	
	public int getRollNo() {
		return rollNo;
	}
	public void setRollNo(int rollNo) {
		this.rollNo = rollNo;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public static String getBranch() {
		return branch;
	}
	public static void setBranch(String branch) {
		Student.branch = branch;
	}
}

public class Test {

	public static void main(String[] args) {

		Student s1 = new Student();
		s1.setRollNo(110);
		s1.setName("Joe");
		Student.setBranch("Computer Engineering");
		System.out.println("Branch :" + Student.getBranch());
		System.out.println("Roll No. :" + s1.getRollNo() + " Name : " + s1.getName());
		Student s2 = new Student();
		s2.setRollNo(111);
		s2.setName("James");
		System.out.println("Roll No. :" + s2.getRollNo() + " Name : " + s2.getName());
	}
}

Instance Variables and Class Variables in C#.NET:

Data Hiding or Data Encapsulation is achieved by declaring fields with the private access modifier. It can be only accessed and processed within the member-functions or methods of the class. C#.NET provide a feature termed Properties to get and set the values of the instance and class variables as demonstrated in the C#.NET program below:


using System;

namespace Test
{
	class Student 
	{
	  public int RollNo {get; set; }
	  public string Name{get; set;}
	  public static string Branch{get; set;}
	}
	public class Program
	{
		public static void Main(string[] args)
		{
		      Student s1 = new Student();
                      s1.RollNo =101;
                      s1.Name ="Joe";
                      Student.Branch = "Computer Engineering";
                      Console.WriteLine("Branch :" + Student.Branch);
                      Console.WriteLine("Roll No. " + s1.RollNo + " Name :" + s1.Name);
                      Student s2 = new Student();
                      s2.RollNo =102;
                      s2.Name ="James";
                      Console.WriteLine("Roll No. " + s2.RollNo + " Name :" + s2.Name);
		}
	}
}

Instance Variables and Class Variables in VB.NET:

VB.NET also similar to C#.NET has the feature of Property to get and set the values of the instance and class variables of the class. However the class members or class variables are declared with the Shared keyword. The example discussed in this post is implemented in VB.NET and is demonstrated in the following code:

Public Class Student
    'Instance Fields or Variable
    Private rno As Integer
    Private nm As String
    'Class Field or variable
    Private Shared br As String

    Public Property RollNo() As Integer
        Get
            Return rno
        End Get
        Set(value As Integer)
            rno = value
        End Set
    End Property

    Public Property Name() As String
        Get
            Return nm
        End Get
        Set(value As String)
            nm = value
        End Set
    End Property
    Shared Property Branch() As String
        Get
            Return br
        End Get
        Set(value As String)
            br = value
        End Set
    End Property
End Class

Module Module1

    Sub Main()
        
        Dim s1 As New Student
        s1.RollNo = 101
        s1.Name = "Joe"
        Student.Branch = "Computer Engineering"
        Console.WriteLine("Branch :" + Student.Branch)
        Console.WriteLine("Roll No. : " & s1.RollNo & " Name : " & s1.Name)
        Dim s2 As New Student
        s2.RollNo = 102
        s2.Name = "James"
        Console.WriteLine("Roll No. : " & s2.RollNo & " Name : " & s2.Name)
        Console.ReadKey()

    End Sub

End Module

Instance Variables and Class Variables in Python:

Python provides a more concise way to define and access class attributes using property methods. 
Python uses  @property decorator to create a getter method for an attribute. This allows  to retrieve the value of the attribute using a getter method without using parentheses to access the field.
The setter method uses the @<attribute_name>.setter decorator. It allows modifying the attribute's value. It can even perform validation or other logic if needed. 

class Person:

    def __init__(self, name):

        self._name = name  # Private attribute with an underscore

    @property

    def name(self):

        return self._name

    @name.setter

    def name(self, new_name):

        if new_name != "":

            self._name = new_name


The example discussed in this post is implemented in Python and is demonstrated in the following code:

class Student:
    #Class Variable
    branch = ""
    def __init__(self):
         self._rollno = 0 # Private attribute with an underscore
         self._name = ""  
        
    def __init__(self, rollno, name):
        self._rollno = rollno # Private attribute with an underscore
        self._name = name  
    @property
    def rollno(self):
        return self._rollno
    @rollno.setter
    def rollno(self, new_rno):
        if new_rno != "":
            self._rollno = new_rno
    @property
    def name(self):
        return self._name
    @name.setter
    def name(self, new_name):
        if new_name != "":
            self._name = new_name

Student.branch = "Computer Engineering"
# Creating a Person object
student = Student(0, "")

# Modifying the attribute using the setter method
student.rollno = 101
student.name = "Joe"
print("Branch :" ,Student.branch)
print("Roll No. " ,student.rollno, " Name :", student.name) 
student.rollno = 102
student.name = "James"
print("Roll No. " ,student.rollno, " Name :", student.name) 

Instance Variables and Class Variables in PHP:

In PHP, One can create getter and setter methods for class fields or properties to encapsulate access to the declared properties. The methods allow controlling how properties are accessed and modified and thereby maintaining data encapsulation.

A Getter method is defined as a method t0 retrieve the value of a property. The naming convention for getter method is like getPropertyName, where PropertyName is the name of the property to be accessed. Similarly for Setter , the name convention is setPropertyName.






<?php

class Person {
    private $rollNo;
    private $name;
    public static $branch;  // Static property
    public function setRollNo($newRollNo) {
        $this->rollNo = $newRollNo;
    }
    public function getRollNo() {
        return $this->rollNo;
    }
    public function setName($newName) {
        if ($newName != "") {
            $this->name = $newName;
        }
    }
    public function getName() {
        return $this->name;
    }
}

Person::$branch = "Computer Engineering";
// Creating a Person object
$person = new Person();
$person->setRollNo(101);
$person->setName("Joe");
echo "Branch :".Person::$branch;
echo "\nRoll No. :".$person->getRollNo();
echo " Name :" .$person->getName(); 
$person->setRollNo(102);
$person->setName("James");
echo "\nRoll No. :".$person->getRollNo();
echo " Name :" .$person->getName(); 

?>
The conclusion is that this post demonstrates the usage of instance variables and class variables in object-oriented languages and its implementation in different object-oriented languages. The output of all of these programs is -

Branch :Computer Engineering
Roll No. :101 Name :Joe
Roll No. :102 Name :James
Instance Variables and Class Variables Reviewed by Syed Hafiz Choudhary on October 10, 2023 Rating: 5

1 comment:

Contact Form

Name

Email *

Message *

Powered by Blogger.