Search code examples
javaclassoopobjectaccess-specifier

How to differentiate between the private instance variable and a parameter having same name in java


There is a keyword this in java to access the instant variables which are public. But is there such way to access the private ones

class Foo {

    private int a = 2;
    public int b = 3;

    public void test(int a, int b) {
        this.b = b;
        //but how to access a;
    }

    public static void main(String args[]) {
        Foo x = new Foo();
        x.test(1, 2);
    }
}

Above is the code example I have....


Solution

  • Within the same class, both private and public variables can be accessed in the same way:

    class Foo {
    
        private int a = 2;
        public int b = 3;
    
        public void test(int a,int b){
            this.b = b;
            this.a = a; // accessing private field a
        }
    
        public static void main(String args[]){
            Foo x = new Foo();
            x.test(1,2);
        }
    }