Victor L
Victor L

Reputation: 10230

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

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

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?

Upvotes: 191

Views: 158765

Answers (12)

CodeKiller
CodeKiller

Reputation: 107

Very old question but still interesting.

Technically (when you code I mean) there is no difference between a field, an attribute or a property.

Depending on the language the 3 can be the same (from tech point of view, not functional PoV).

The 3 words design something related to an object in general. For instance Eclipse call everything outside a method a "field".

  • Property

In VisualBasic, all the attributes of an object are properties (font size, color, etc.). Example from Microsoft website about VB:

A property is an attribute of an object that defines one of the object's characteristics, such as size, color, or screen location, or an aspect of its behavior, such as whether it is enabled or visible.

So a "property" is an "attribute" (but an attribute is not necessarily a property). Attribute is just a generic term to describe something related to an object but which not define the object itself while a property design something that define an object.

For instance the property of a fabric to block water it is a property of this fabric.

The fact a human being has 2 arms, 2 legs and 2 eyes are properties. yu can still lose them but they define the object "HumanBeing"

  • Field is linked to an instance of an object but does not design a property of the object.

A "field" could be the length of a piece of the fabric. The length itself is not related to the fabric and only used at the time the object is created. So you can have 3 fabrics with the same property (waterproof as a boolean) but 3 different field length for 3 customers. And you can even cut the fabric so the length will decrease.

Other examples : a car has a "color" property (should not change by itself at least) but a "remainingGaz" field as it can change at any time.

The color of the hairs for a human can also a field as you can dye them if you want, not like cutting an arm and putting it back as you want.

Imagine this piece of code :

if (hasDyedHair())
    return getDyeColor(); // Not mandatory use can be called a "field"
else
    return getHairColor(); // Mandatory use as everyone borns with hairs in theory can be called "property"
  • Variable

Easiest thing to understand: temporary object to work with. Created and destroyed on the fly to store temporary values to do some calculus etc.

Basically if it is not linked to the object you are working in then it is a variable. Mostly used in a service or this kind of class which does not describe a functional object. Imagine you want to paint a house, you must check if you are allowed to do it (in a PaintHouse() methode for instance), so you will search for stuff like owner of the house, laws about house design if exists, etc. you store all of that locally so they are variables and not related to the paint itself and use them like "if owner = me and if lawIsOk and...".

I hope this long answer will help people.

Upvotes: 1

Sagar Patel
Sagar Patel

Reputation: 586

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:-

https://web.archive.org/web/20150726222007/http://sajupauledayan.com/java/fields-vs-variables-in-java

Upvotes: 3

yoAlex5
yoAlex5

Reputation: 34301

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...]

Upvotes: 1

rarora25
rarora25

Reputation: 99

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.

Upvotes: 4

Adam Gent
Adam Gent

Reputation: 49095

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 :)

Upvotes: 121

vimal krishna
vimal krishna

Reputation: 2966

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.

Upvotes: 5

Koray Tugay
Koray Tugay

Reputation: 23800

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.

Upvotes: 0

Peter Clause
Peter Clause

Reputation: 1141

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.

Upvotes: 0

Mango
Mango

Reputation: 59

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)

Upvotes: 5

the_prole
the_prole

Reputation: 8985

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    

    }    
}

Upvotes: 2

hotshot309
hotshot309

Reputation: 1728

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.

Upvotes: 6

jahroy
jahroy

Reputation: 22692

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.

Upvotes: 132

Related Questions