Java Bean encapsulates many objects into one,How?

Meh Sar :

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:

From Java Beans Wikipedia:

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.

Nexevis :

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<String> list;

    //Omitted rest of bean boilerplate
}

This example will contain two different Objects inside of it, the String s and the ArrayList<String> 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<String> 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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12220&siteId=1