How to access a variable from another class method in Java

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900

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 cadence, gear, 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

This makes it clear that they are class variables.

Note: You can also refer to static fields with an object reference like 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.

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; } }

I've found some answers to my question on google, but the only "answers" that I found didn't help me much at all.

Rather than putting code to get screen dimensions in several classes, I figured that I would define one class to use as a splash screen, assign the screen dimensions to variables in that class, and then reference those variables from other classes. Is this possible?

In this article, we will learn how to access variable from another class in java.

There are two ways to get variables from another class.

  1. Create an object of another class in the main class
  2. Extend another class in the main class

Let us take a look at both these methods one by one with the help of sample programs.

Method 1: Create Object of Another Class in Main Class

In the following example, to access the variable ‘a’ of class A, we create its object in another class B. After that, we use this object to use the value of variable ‘a’ in class B. Note that if we do not initialize this variable, then its default value is taken to be zero.

Syntax:

Program:

//Parent class class A {     int a = 10;//instance variable } //Child class class B{         public static void main(String[] args)         {              A obj = new A();              System.out.println(obj.a);         }  }

    int a = 10;//instance variable

        public static void main(String[] args)

             System.out.println(obj.a);

Output:

Method 2: Extend Another Class in Main Class

If we wish to access a variable from another class, we have a keyword, ‘extends’, which we can use in the child class. Using it, the child class can inherit all the properties of the parent class.

Syntax:

public class_A extends class_B

public class_A extends class_B

Program:

// parent class class A { int a = 10; //instance variable } // child class class B extends A { public static void main(String args[]) { B obj = new B(); System.out.println(obj.a); } }

    int a = 10; //instance variable

    public static void main(String args[])

        System.out.println(obj.a);

Output:

In the above program, we created two classes, namely ‘A’ and ‘B’. In class ‘A’, we defined an instance variable ‘a’ with a value of 10. The other class ‘B’, extends the class ‘A’ using the ‘extends’ keyword. So, it can use the instance variable of class ‘A’ by creating its object. So, the child class inherits all the properties of its parent class.

If we wish to use an instance variable, then we have to use objects to call them. Every time you create a new object from a class, you get a new copy of each of the class’s instance variables. These copies are associated with the new object. So, each and every instance variable is accessed by the object.

Program:

class A { int a ; //instance variable } public class B extends A { public static void main(String args[]) { B obj = new B(); System.out.println(obj.a); obj.a = 3; System.out.println(obj.a); } }

    int a ; //instance variable

public class B extends A {

    public static void main(String args[])

        System.out.println(obj.a);

        System.out.println(obj.a);

Output:

In the above example, the default value of a is 0 and we updated its value to 3 using an object.

So, that’s all about accessing variables from another class.

Toplist

Latest post

TAGs