Does Java have "properties" that work the same way properties work in C# (see the body of my text)?

Posted by tyrone302 on Stack Overflow See other posts from Stack Overflow or by tyrone302
Published on 2010-04-23T18:33:46Z Indexed on 2010/04/23 18:43 UTC
Read the original article Hit count: 116

Filed under:
|
|

In C#, you can use properties to make a data field publicly accessible (allowing the user to directly access it), and yet retain the ability to perform data validation on those directly-accessed fields. Doese Java have something similar? For Instance, suppose there exists a C# class with the following implementation(see below):

public class newInt{

    public newInt(){...}

    public int x{
        get{ return this.x }
        set{ this.x = isValid(value) }
    }
}

private static int isValid(int value){...}

This definition in the class allows the user to "naturally" use the data field 'x' when retrieving values from it and assigning values to it. Below is how it would be used in main.

public class Test{

    public static void main(String[] args){

        newInt a = new newInt();
        a.x = 50;

        int b = a.x;
    }
}

The question is... can java do this as well? if so, what is it called?

© Stack Overflow or respective owner

Related posts about c#

Related posts about properties