What is the difference between field, variable, attribute, and property in Java POJOs?
Asked Answered
T

11

189

When referring to internal private variables of Java POJOs that have getters/setters, I've used the following terms:

  • field
  • variable
  • attribute
  • property

Is there any difference between the above? If so, what is the correct term to use? Is there a different term to use when this entity is persisted?

Taurus answered 11/4, 2012 at 23:51 Comment(0)
E
131

From here: http://docs.oracle.com/javase/tutorial/information/glossary.html


  • field

    • A data member of a class. Unless specified otherwise, a field is not static.

  • property

    • Characteristics of an object that users can set, such as the color of a window.

  • attribute

    • Not listed in the above glossary

  • variable

    • An item of data named by an identifier. Each variable has a type, such as int or Object, and a scope. See also class variable, instance variable, local variable.
Eh answered 12/4, 2012 at 0:6 Comment(10)
I still do not understand the difference between a field and a property?Orderly
@KorayTugay - Look at a field as a rudimentary piece of data related to an object. A property (to me) is a characteristic of an object that is visible (and apparently mutable) to the outside world.Eh
Based on the above, would it be fair to say "Properties and fields are the same, except a property is a settable field"?Opportuna
@John - Maybe based on the above, which, as noted, is a copy/paste from Oracle. Personally I'd make the distinction that a property is publicly visible and possibly mutable, whereas a field could be an internal, private field used only by the class.Eh
I think the best thing to stress is that existence as a field and a property is not mutually exclusive. From the way this answer is worded, to new developers, it looks like a list of distinct things.Saber
@jahroy, Is it safe to say that a field can be property when it is public and also not final ? or can we say that a field with a getter and setter is a property ?Cheke
I didn't like the "field" definition. Although, in the glossary, "instance variable" is defined as: *Any item of data that is associated with a particular object. Each instance of a class has its own copy of the instance variables defined in the class. Also called a field. * I like that one better.Featherhead
@KorayTugay A property is also a field, but a field is not necessary a property. Property is a hyponym of field (and field is a hypernym of property). A field is also a property, when its value can be set (typically with a setter method).Sulk
I think fields are "helper" attributes (such as singletons, constants, utilities classes, loggers) that are not really related to the world definition of the object, but technically to the application itself, whereas attributes/properties define real characteristics of the abstracted object.Heptarchy
Have on mind, that there can be property (i.e. some setter) in class, which is not being backed by any field! I.e. some setStatus(DISABLED) call can do some business logic and NOT save given parameter directly to some field.Laccolith
S
119

Yes, there is.

Variable can be local, field, or constant (although this is technically wrong). It's vague like attribute. Also, you should know that some people like to call final non-static (local or instance) variables

"Values". This probably comes from emerging JVM FP languages like Scala.

Field is generally a private variable on an instance class. It does not mean there is a getter and a setter.

Attribute is a vague term. It can easily be confused with XML or Java Naming API. Try to avoid using that term.

Property is the getter and setter combination.

Some examples below

public class Variables {

    //Constant
    public final static String MY_VARIABLE = "that was a lot for a constant";

    //Value
    final String dontChangeMeBro = "my god that is still long for a val";

    //Field
    protected String flipMe = "wee!!!";

    //Property
    private String ifYouThoughtTheConstantWasVerboseHaHa;

    //Still the property
    public String getIfYouThoughtTheConstantWasVerboseHaHa() {
        return ifYouThoughtTheConstantWasVerboseHaHa;
    }

    //And now the setter
    public void setIfYouThoughtTheConstantWasVerboseHaHa(String ifYouThoughtTheConstantWasVerboseHaHa) {
        this.ifYouThoughtTheConstantWasVerboseHaHa = ifYouThoughtTheConstantWasVerboseHaHa;
    }

}

There are many more combinations, but my fingers are getting tired :)

Starfish answered 11/4, 2012 at 23:55 Comment(5)
@Chris Thompson Thats what Eclipse calls it in one of its dialog. Hey folks its Java. What can I tell you. It doesn't make sense.Starfish
@AdamGent JAVA=Just Another Vague Acronym :)Chesterfieldian
@Chesterfieldian Well it's the old well known oxymoron. That's nothing specific to Java, that "problem" goes back till at least C and probably longer.. obviously nothing stops you from calling it just "constant"Backfield
@AdamGent Wasn't serious, just giving you a hard time ;-)Hays
Good explanation while making fun of how identifier names can get ridiculously long (and they DO get ridiculously long often).Polysyllable
D
6

If your question was prompted by using JAXB and wanting to choose the correct XMLAccessType, I had the same question. The JAXB Javadoc says that a "field" is a non-static, non-transient instance variable. A "property" has a getter/setter pair (so it should be a private variable). A "public member" is public, and therefore is probably a constant. Also in JAXB, an "attribute" refers to part of an XML element, as in <myElement myAttribute="first">hello world</myElement>.

It seems that a Java "property," in general, can be defined as a field with at least a getter or some other public method that allows you to get its value. Some people also say that a property needs to have a setter. For definitions like this, context is everything.

Disorganization answered 1/5, 2013 at 21:32 Comment(0)
E
5

Dietel and Dietel have a nice way of explaining fields vs variables.

“Together a class’s static variables and instance variables are known as its fields.” (Section 6.3)

“Variables should be declared as fields only if they’re required for use in more than one method of the class or if the program should save their values between calls to the class’s methods.” (Section 6.4)

So a class's fields are its static or instance variables - i.e. declared with class scope.

Reference - Dietel P., Dietel, H. - Java™ How To Program (Early Objects), Tenth Edition (2014)

Ernieernst answered 10/2, 2016 at 9:24 Comment(0)
M
5

If you take clue from Hibernate:

Hibernate reads/writes Object's state with its field. Hibernate also maps the Java Bean style properties to DB Schema. Hibernate Access the fields for loading/saving the object. If the mapping is done by property, hibernate uses the getter and setter.

It is the Encapsulation that differentiates means where you have getter/setters for a field and it is called property, withthat and we hide the underlying data structure of that property within setMethod, we can prevent unwanted change inside setters. All what encapsulation stands for...

Fields must be declared and initialized before they are used. Mostly for class internal use.

Properties can be changed by setter and they are exposed by getters. Here field price has getter/setters so it is property.

class Car{
 private double price;
 public double getPrice() {…};
 private void setPrice(double newPrice) {…};
}

<class name="Car" …>
<property name="price" column="PRICE"/>
</class>

Similarly using fields, [In hibernate it is the recommended way to MAP using fields, where private int id; is annotated @Id, but with Property you have more control]

class Car{
  private double price;
}
<class name="Car">
<property name=" price" column="PRICE" access="field"/>
</class>

Java doc says: Field is a data member of a class. A field is non static, non-transient instance variable. Field is generally a private variable on an instance class.

Maui answered 28/12, 2016 at 20:1 Comment(1)
And in Hibernate the term attribute also has a meaning: fields or properties that are persisted are called persistent attributes "[...] all the state of an entity is made up entirely of value types. These state fields or JavaBean properties are termed persistent attributes."Milldam
G
4

The difference between a variable, field, attribute, and property in Java:

A variable is the name given to a memory location. It is the basic unit of storage in a program.

A field is a data member of a class. Unless specified otherwise, a field can be public, static, not static and final.

An attribute is another term for a field. It’s typically a public field that can be accessed directly.

  • In NetBeans or Eclipse, when we type object of a class and after that dot(.) they give some suggestion which are called Attributes.

A property is a term used for fields, but it typically has getter and setter combination.

Glimmer answered 29/12, 2020 at 15:25 Comment(0)
V
2

Variables are comprised of fields and non-fields.

Fields can be either:

  1. Static fields or
  2. non-static fields also called instantiations e.g. x = F()

Non-fields can be either:

  1. local variables, the analog of fields but inside a methods rather than outside all of them, or
  2. parameters e.g. y in x = f(y)

In conclusion, the key distinction between variables is whether they are fields or non-fields, meaning whether they are inside a methods or outside all methods.

Basic Example (excuse me for my syntax, I am just a beginner)

Class {    
    //fields    

    method1 {              
         //non-fields    

    }    
}
Vesicate answered 29/8, 2013 at 21:20 Comment(0)
M
2

Actually these two terms are often used to represent same thing, but there are some exceptional situations. A field can store the state of an object. Also all fields are variables. So it is clear that there can be variables which are not fields. So looking into the 4 type of variables (class variable, instance variable, local variable and parameter variable) we can see that class variables and instance variables can affect the state of an object. In other words if a class or instance variable changes,the state of object changes. So we can say that class variables and instance variables are fields while local variables and parameter variables are not.

If you want to understand more deeply, you can head over to the source below:-

http://sajupauledayan.com/java/fields-vs-variables-in-java

Morry answered 10/2, 2016 at 10:9 Comment(1)
Link in answer is dead.Hysteric
O
1

Java variable, field, property

  • variable - named storage address. Every variable has a type which defines a memory size, attributes and behaviours. There are for types of Java variables: class variable, instance variable, local variable, method parameter
//pattern
<Java_type> <name> ;

//for example
int myInt;
String myString;
CustomClass myCustomClass;
  • field - member variable or data member. It is a variable inside a class(class variable or instance variable)

  • attribute - in some articles you can find that attribute it is an object representation of class variable. Object operates by attributes which define a set of characteristics.

CustomClass myCustomClass = new CustomClass();
myCustomClass.myAttribute = "poor fantasy"; //`myAttribute` is an attribute of `myCustomClass` object with a "poor fantasy" value

[Objective-C attributes]

  • property - field + bounded getter/setter. It has a field syntax but uses methods under the hood. Java does not support it in pure form. Take a look at Objective-C, Swift, Kotlin

For example Kotlin sample:

//field - Backing Field
class Person {
    var name: String = "default name"
        get() = field
        set(value) { field = value }
}

//using
val person = Person()
person.name = "Alex"    // setter is used
println(person.name)    // getter is used

[Swift variable, property...]

Oystercatcher answered 28/3, 2020 at 22:13 Comment(0)
M
0

The question is old but another important difference between a variable and a field is that a field gets a default value when it's declared.A variable, on the other hand, must be initialized.

Masquer answered 8/3, 2016 at 12:21 Comment(1)
How about a property?Orderly
O
0

My understanding is as below, and I am not saying that this is 100% correct, I might as well be mistaken..

A variable is something that you declare, which can by default change and have different values, but that can also be explicitly said to be final. In Java that would be:

public class Variables {

    List<Object> listVariable; // declared but not assigned
    final int aFinalVariableExample = 5; // declared, assigned and said to be final!

    Integer foo(List<Object> someOtherObjectListVariable) {
        // declare..
        Object iAmAlsoAVariable;

        // assign a value..
        iAmAlsoAVariable = 5;

        // change its value..
        iAmAlsoAVariable = 8;

        someOtherObjectListVariable.add(iAmAlsoAVariable);

        return new Integer();
    }
}

So basically, a variable is anything that is declared and can hold values. Method foo above returns a variable for example.. It returns a variable of type Integer which holds the memory address of the new Integer(); Everything else you see above are also variables, listVariable, aFinalVariableExample and explained here:

A field is a variable where scope is more clear (or concrete). The variable returning from method foo 's scope is not clear in the example above, so I would not call it a field. On the other hand, iAmAlsoVariable is a "local" field, limited by the scope of the method foo, and listVariable is an "instance" field where the scope of the field (variable) is limited by the objects scope.

A property is a field that can be accessed / mutated. Any field that exposes a getter / setter is a property.

I do not know about attribute and I would also like to repeat that this is my understanding of what variables, fields and properties are.

Orderly answered 20/12, 2016 at 16:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.