class

Access outer variables example

This is an example of how to access outer variables in a class. The example is described in short:

  • We have created a class, OuterVars that has an int field cnt, an inner class Cnt, and a method go()
  • Cnt class has a field cnt, a method increment() that increases its cnt and the cnt field of OuterVars. It also has a method dispValues() that prints out the values of the two fields.
  • OuterVars class has a method go() that creates a new instance of Cnt and calls increment() and go() methods.
  • We create a new instance of OuterVars and call its go() method. In go() method a new Cnt is created and the increment() method is called three times.
  • When the Cnt is created its cnt field is initialized to 10, whereas when the OuterVars is created its cnt field is initialized to 0. So after calling three times increment() method the inner cnt is set to 13 and the outer is set to 3.

Let’s take a look at the code snippet that follows:  

package com.javacodegeeks.snippets.core;

public class OuterVars {

    int cnt = 0;

    public static void main(String args[]) {

  OuterVars otv = new OuterVars();

  otv.go();
    }
    

    public class Cnt {


  int cnt = 10;


  public void increment() {


cnt++;


OuterVars.this.cnt++;

  }


  public void dispValues() {


System.out.println("Inner: " + cnt);


System.out.println("Outer: " + OuterVars.this.cnt);

  }
    }

    public void go() {

  Cnt counter = new Cnt();

  counter.increment();

  counter.increment();

  counter.increment();

  counter.dispValues();
    }
}

Output:

Inner: 13
Outer: 3

  
This was an example of how to access outer variables in a class in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button