1

Usually, if type is a private member of a class named Pass, and obj is a reference to object of Pass class, we cannot do obj.type because type is private member so that would give error.

In copy() method, a is passed as a parameter where a is a reference to Pass object.

By the same logic, we should also not be allowed to do a.type.

But this code runs fine. Why? This is my doubt.

public class Main {

    public static void main(String[] args) {
    Pass ob1 = new Pass(10,'c');
    Pass ob2 = new Pass(20,'f');

    ob1.print();
    ob2.print();

    ob1.copy(ob2);

    ob1.print();
    ob2.print();
    }
}

class Pass {
    private int number = 0;
    private char type = 'a';

    public Pass(int i, char t) {
        this.number = i;
        this.type = t;
    }

    public void copy(Pass a) {
        this.number = a.number;
        this.type = a.type;
    }

    public void print() {
        System.out.println(number + " =>" + type);
    }
}
  • 3
    private means that something can only becaccessed by things in the same class. Not only from the same object. – dan1st May 27 '21 at 20:29
  • 5
    Visibility modifiers describe *class* visibility, not *object* visibility. – Pshemo May 27 '21 at 20:30
  • 1
    They're not being accessed outside their class. You're confusing 'class' and 'object' (or 'instance'). – iggy May 28 '21 at 02:50

2 Answers2

4

There are four types of Java access modifiers:

  1. Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
  2. Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.
  3. Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.
  4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package, and outside the package.

In your case, you access the type variable inside the Pass class. So even though it is a private variable, you have permission to access it.

Rukshan Jayasekara
  • 1,945
  • 1
  • 6
  • 26
3

Because the method is in the same class, it can access private members of other instances. private only means that only functions in the class can access it, with no restrictions on which object is doing the accessing.

Adam Abahot
  • 176
  • 3