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 fieldcnt
, an inner classCnt
, and a methodgo()
. Cnt
class has a fieldcnt
, a methodincrement()
that increases itscnt
and thecnt
field ofOuterVars
. It also has a methoddispValues()
that prints out the values of the two fields.OuterVars
class has a methodgo()
that creates a new instance ofCnt
and callsincrement()
andgo()
methods.- We create a new instance of
OuterVars
and call itsgo()
method. Ingo()
method a newCnt
is created and theincrement()
method is called three times. - When the
Cnt
is created itscnt
field is initialized to 10, whereas when theOuterVars
is created itscnt
field is initialized to 0. So after calling three timesincrement()
method the innercnt
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.