java封装为so,Java Bean将许多对象封装为一个,如何?

I'm newly started reading about Java Beans and I had a question which was exactly same as this Topic's question. So I repeat The question:

in definition it is said "java bean encapsulates many objects into one object(Bean)."

1.What does "many objects" here mean?

and

2.How they are encapsulated into one object by java beans?

Edit:

in computing based on the Java Platform, JavaBeans are classes that encapsulate many objects into a single object (the bean).

Edit2:

all of classes have ability of having multiple attributes and fields.

If encapsulating of many objects means having multiple attributes and fields, I don't understand why they mentioned to this ability as a advantage of java bean class.

解决方案

First to make it clear, every Class in Java extends the type Object. Something like String is also an Object.

The "many objects" is referring to how we can use different objects as fields within the bean. This creates a has-a relationship with the bean to your Objects.

For example, say we have this Bean:

public class YourBean implements java.io.Serializable {

private String s;

private ArrayList list;

//Omitted rest of bean boilerplate

}

This example will contain two different Objects inside of it, the String s and the ArrayList named list. You can add as many different Objects and primitives to your bean as you want.

To create the bean with a no-args constructor, you would then use:

YourBean bean = new YourBean();

And you can set and get the values of the Objects encapsulated within with:

ArrayList yourList = new ArrayList<>();

bean.setList(yourList);

System.out.println(bean.getList());

You will be able to refer to all the Objects inside the bean this way by referencing the bean Object I named bean.

Additionally, you can create multiple of the same type of bean as well, so every time you make a new YourBean(), you will also be able to use all the Objects contained within.

This functionality is not unique to a Bean, you can do this in any Class, rather a Bean is a term used to describe a specific way you write some classes.

I recommend looking into Java Composition to learn when you should use a has-a relationship, rather than inheritance which is an is-a relationship.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值