Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java have "properties" that work the same way properties work in C#?

Tags:

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?

like image 657
tyrone302 Avatar asked Apr 23 '10 18:04

tyrone302


People also ask

How Does properties work in Java?

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.

Is there properties in Java?

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.

What is Property and method in Java?

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.


1 Answers

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; } } 
like image 127
Justin Niessner Avatar answered Oct 04 '22 18:10

Justin Niessner