-1

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....

deHaar
  • 17,687
  • 10
  • 38
  • 51

5 Answers5

2

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);
    }
}
Thomas Francois
  • 866
  • 6
  • 21
Ankur
  • 892
  • 6
  • 11
  • can I do x.a inside main – gopinadh5g7 Aug 31 '18 at 11:39
  • @gopinadh5g7 No you cannot. That is the difference between public and private access modifiers. Private variables are only accessible within the class itself. Please refer https://docs.oracle.com/javase/tutorial/java/javaOO/variables.html – Ankur Aug 31 '18 at 12:14
  • this is equal to object then how is it possible – gopinadh5g7 Aug 31 '18 at 12:16
  • @gopinadh5g7, yes you are right.You can do x.a. I didn't realize main method was in Foo class itself. – Ankur Aug 31 '18 at 12:30
  • 1
    Sorry I got it this is a keyword and can acess any attribute in the class and never minds what access specifier it is – gopinadh5g7 Aug 31 '18 at 12:30
1

All class methods have access to their own private members. Hence, this.a = a will work.

selbie
  • 100,020
  • 15
  • 103
  • 173
1

Follow Java tutorial on this keword it can access private members:

private int x, y;
public Rectangle(int x, int y, int width, int height) {
   this.x = x;
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
0

A class object can access it's private members, otherwise nothing could access them and they'd be quite pointless. So this with private members works absolutely fine.

Max Vollmer
  • 8,412
  • 9
  • 28
  • 43
0

Class method have an access to private data member so you can use

this.a=a
Snehal Patel
  • 1,282
  • 2
  • 11
  • 25