3

I have the following two classes. Can I say the first one is a POJO class and the second one as a Bean class?

1) POJO class, since it has only getter and setter method, and all the member are declared as private

public class POJO {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setId() {
        this.id = id;
    }

    public void setName() {
        this.name = name;
    }
}

2) Bean class - all the member variables are private, has getters and setters and implements Serializable interface

public class Bean implements java.io.Serializable {
    private String name;
    private Integer age;

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return this.age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

It also has a no-arg constructor.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Vishnu
  • 176
  • 1
  • 2
  • 19

2 Answers2

9

Only difference is bean can be serialized.

From Java docs - http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html

Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.

Ninad Pingale
  • 6,801
  • 5
  • 32
  • 55
  • 1
    that means if i implement java.io.Serializable interface , it is a bean otherwise a pojo class. @ninad Pingale – Vishnu Aug 18 '14 at 11:58
  • And the bean, need a constructor, without arguments :) –  Jul 19 '17 at 06:27
3

the JavaBean class must implement either Serializable or Externalizable, must have a no-arg constructor,all JavaBean properties must public setter and getter methods (as appropriate) all JavaBean instance variables should be private

phani
  • 161
  • 1
  • 10
  • can i have a example for no-arg constructor. Thanks in advance – Vishnu Aug 18 '14 at 11:09
  • 1
    public class TestBean implements java.io.Serializable { private String name; /** No-arg constructor (takes no arguments). */ public TestBean() { } public String getName() { return this.name; } public void setName(final String name) { this.name = name; }} – phani Aug 18 '14 at 11:45
  • If no arg constructor is absent in definition of POJO, But Serializable has been implemented in a POJO, would it be considered as a Bean ? – Sachin Feb 08 '16 at 09:17
  • A Javabean SHOULD, not MUST implement Serializable – karlihnos Apr 19 '17 at 16:13