Member variable declaration

Java’s member variables are all declared outside the methods in the class and represent the properties that the object can have.

Member variables consist of static and final as shown below. static means class variable and final means end variable. If static or final is not attached, it means object reference variable or object property variable.

[public/private/protected] [static/final] VariableType VariableName;

public, private, protected is an access modifier and acts like the qualifier introduced in the declaration of a class.

An object variable represents a property that an object can have, separated by object attribute variables and object reference variables. An object property variable is a value that represents an attribute that an object can have, consisting of values from a base type, and an object reference variable is a variable that specifies an object.

In Java, all elements except base types are treated as objects. You can create an object and then access its members through object reference variables to access the object.

Object Property Variables and Object Reference Variables

class Box {
  //Object property variables
  int width;
  int height;
  int depth;
}

class MyBox {
  //Object property variables
  int vol;

  //Object reference variables
  Box mybox1;
  Box mybox2;
  String boxname;
  ...
  public static void main(String args[]) {
    mybox1 = new Box();
    mybox2 = new Box();
    ...
  }
}

Assigning Object Attribute Variables and Object Reference Variables

//Example of assigning object variables
{
  ...
  int my_count1 = 100;
  //Assigning Object Attribute Variables
  int my_count2 = my_count1;

  Box mybox1 = new Box();
  //Assigning Object Reference Variables
  Box mybox2 = mybox1;
}

An object attribute variable is copied and passed the value of a variable, and an object reference variable points to the same object because the address to the object is copied and passed.

class Fruit {
  //Object property variables
  int apple = 5;
  int straw = 10;
  int grapes = 15;
}

class Buy {
  public static void main(String args[]) {
    int quantity1, quantity2;

    Fruit f1 = new Fruit();
    Fruit f2 = f1;
    quantity1 = f1.apple + f1.straw + f1.grapes;
    quantity2 = f2.apple + f2.straw + f2.grapes;

    System.out.println("The initial number of fruits in object f1 " + quantity1 + "ea");
    System.out.println("The initial number of fruits in object f2 " + quantity2 + "ea");

    f1.apple = 10;
    f2.straw = 20;
    f1.grapes = 30;
    quantity1 = f1.apple + f1.straw + f1.grapes;
    quantity2 = f2.apple + f2.straw + f2.grapes;
    System.out.println("Number of values after changing the value of object f1 " + quantity1 + "ea");
    System.out.println("Number of values after changing the value of object f2 " + quantity2 + "ea");
  }
}
Object Property Variable Example

Leave a Reply

Your email address will not be published. Required fields are marked *

Latest Post