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. Does 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?
Properties are configuration values managed as key/value pairs. In each pair, the key and value are both String values. The key identifies, and is used to retrieve, the value, much as a variable name is used to retrieve the variable's value.
Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String. The Properties class is used by many other Java classes. For example, it is the type of object returned by System.
Properties class is the subclass of Hashtable. It can be used to get property value based on the property key. The Properties class provides methods to get data from the properties file and store data into the properties file. Moreover, it can be used to get the properties of a system.
No.
That's why Java has getters/setters.
In C# you typically have something like:
public class SomeObject { private string _title = ""; public string Title { get { return _title; } set { _title = value; } } } // Or with Auto-Properties public class SomeObjectAutoProperties { public string Title { get; set; } }
The Java getter/setter equivalent would be:
public class SomeObject { private String _title = ""; public string getTitle() { return _title; } public void setTitle(String value) { _title = value; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With