Where is the encapsulation?

I am a new programmer, so please excuse any dumbness of this question, how does the following code encapsulate personal data? -

public class SomeClass
{
    private int age;

    public int Age
    {
        get { return age; }
        set { age = value; }
    }

    public SomeClass(int age)
    {
        this.age = age;
    }
}

I mean, without restriction logic or filtering logic in properties, how does this code differ from the following -

public class SomeClass
{
    public int age;

    public SomeClass(int age)
    {
        this.age = age;
    }
}

Is the first code providing any encapsulation at all?

+5
source share
6 answers

It provides one part of encapsulation: it says: "There is an Age property that you can get and set, but I won’t tell you how I implement it."

, API. API, - - short , - , long - . , , . , , ( API , ).

EDIT: : , , - , , . , , . , . . ( , ) , .

, # 3 , :

public int Age { get; set; }

, .

+8

. , .

. , SomeClass Age (, , , -2 823). , SomeClass int . (, ) SomeClass (, , ).

+2

, - , ,

, , , . - .

, , , , .

, API .

+2

age. age , public. , age . , .

+1

SomeClass.Age . "" . SomeClass.age . , API "" . , - ( ) , - .

0

, ?

( , , ).

2 . , ( ).

When using getters and setters, you can restrict access to private variables . This may be a form of encapsulation.

i.e.

private int x

public int getInt(String password){
 if(password == 'RealPassword'){
   return x
  }
}
0
source

All Articles