-1

Suppose we have got a class with a certain private member. When I declare a class method and pass an object of the same type, the method is inside, i am able to access all the private members without getters. For example:

class Human{

 private int age;

   public static int compareAges(Human h1, Human h2){
             h1.age // IS CORRECT, DESPITE age is private in h1. 
                ...
   }
}

Why is it possible?

Vlad
  • 1
  • 2
  • It is not private in h1, it is private in Human. – luk2302 May 28 '22 at 19:23
  • The assumption of the language designer is that if you don't want instance X to access the private fields of instance Y (of the same class), then you don't write code that does that. – dangling else May 28 '22 at 22:07

2 Answers2

4

It is possible because your compareAges Method is inside the Human class. Therfore it can access private property of class Human.

The private keyword only stops other classes to access the property.

This ensures that other classes (could be written by other developers for example) don't accidentaly access these properties. Because you are in the same class, there is no reason to untrust this code.

Laisender
  • 714
  • 1
  • 5
  • 10
0

There aren't any access modifiers that prevent accessing fields within class. You have to work with:

public - access granted for everyone

protected - access within classes that are extending parent class

private - access within class, therefore it is assumed what author of class is trusted enough to access variable