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);
}
}