java POJO和Bean的编程区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25361341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Programming difference between POJO and Bean
提问by Vishnu
I have the following two classes. Can I say the first one is a POJO class and the second one as a Bean class?
我有以下两个课程。我可以说第一个是 POJO 类,第二个是 Bean 类吗?
1) POJO class, since it has only getter and setter method, and all the member are declared as private
1) POJO类,因为它只有getter和setter方法,并且所有成员都声明为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
2) Bean类——所有成员变量都是私有的,有getter和setter,并实现了Serializable
接口
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.
它还有一个无参数构造函数。
回答by Ninad Pingale
Only difference is bean can be serialized.
唯一的区别是 bean 可以序列化。
From Java docs - http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html
来自 Java 文档 - 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.
类的可序列化由实现 java.io.Serializable 接口的类启用。未实现此接口的类将不会对其任何状态进行序列化或反序列化。可序列化类的所有子类型本身都是可序列化的。序列化接口没有方法或字段,仅用于标识可序列化的语义。
回答by phani
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
JavaBean 类必须实现 Serializable 或 Externalizable,必须有一个无参数构造函数,所有 JavaBean 属性必须是公共的 setter 和 getter 方法(视情况而定)所有 JavaBean 实例变量都应该是私有的