3

When I checked different sites about java bean, I see it says its a piece of reusable components but what does reusable components mean in practical. I couldn't find in which way it is reusable neither I got any examples describing the same. Please provide an example for this. Java bean has getter and setter method so in which sense it is reusable?

public JavaBean{
    public String msg;
    public JavaBean()
    {
        msg="hwllo";
    }
    public string getMsg()
    {
        retrun msg;
    }
    public void setmsg(String msg)
    {
        this.msg=msg;
    }
}

5 Answers5

0

"reusable" means that you can use the code in many different projects. For example, all Swing components are also Java Beans. You can use a JFrame is as many programs as you wish.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • you said all swing components are also javabeans but swing components does not have getter and setter methods –  Feb 22 '13 at 06:45
0

java beans are simple java classes which comply to certain rules like:

1) no arg (default) public constructor 2) For each property there should be an accessor (get) and a mutator (set) methods 3) Get/Set methods should follow a certain naming convention 4) Class should be serializable

If you follow these rules then other (potentially 3rd party) software can discover the capabilities of your class at runtime and reuse it. E.g. struts tags are simple java beans which are being reused in many web applications. Usually, Java Beans are executed in some kind of container which manages it life-cycle, like creation, method invocation, destroying etc. Containers (e.g. servlet container, spring container etc) can instantiate your class and populate its properties even before you actually use it in your code. In that way lot of boilerplate/repetitive logic (creation of objects, population of properties) is taken out of the code which is reusing it.

Bimalesh Jha
  • 1,464
  • 9
  • 17
  • can you desribe with reference to the code i have posted/? can you please how it is reusable? –  Feb 22 '13 at 07:06
  • your `setmsg()` is wrong. It is not a bean :-) Anyways, first of all a bean has to be really "useful" to become reusable. Your bean is not doing anything useful. Hence, difficult to cite practical reuse of it. However, consider this- let say I have a "MessagePlayer" class which takes in your class and just finds what all it properties (e.g. msg) here and invokes it. I don't have to write getter/setter myself. There may be associated logic with msg like it should be 100 characters long etc. all this logic can be in your bean. MessagePlayer need not worry about it. It is just calling your class. – Bimalesh Jha Feb 22 '13 at 07:16
  • see i have class for example print public class print{ public void static main(String args[]) { System.out.println("print"); } } see this code can we used any where to print so can we call it as reusable? –  Feb 22 '13 at 07:22
0

Reusable components are simply pre-built pieces of programming code designed to perform a specific function.
Beans are "capsules" of code, each designed for a specific purpose. The advantage of Java Beans over standard programming controls is that Beans are independent and are not specific to operating systems or development environments. A Bean created in one development environment can be easily copied and modified by another. This allows Java Beans greater flexibility in enterprise computing, as components are easily shared between developers. An exciting concept behind Beans springs from the fact that an application created in Java can be used as a Bean, which can be used to build other applications.

zapbuild
  • 182
  • 4
0

Java Bean and reusable component are about slightly different things. Many words said there about Java Beans, please take a look. Finally - it is just a set of conventions, which some frameworks, applications and other programmers :) expect from your code. Nothing else.

Reusable component is more general, means you can reuse your code in different parts of your system/application. Or even other applications can use your code, exposed as an API. Simple utility class to work with strings, some domain object (e.g. class Student, oh, Java Bean is also there!), some email sending service, XML parser - all of them are reusable components.

UPD. Answering the question from comments, simple print reusable component

public class OutStd {

  public static void print(String string) {
      System.out.println(string);
  }

}

public class SomeOtherComponent() {

  public void doSomeImportantStuff() {
    // reuse existing print functionality
    OutStd.print("Some string");
    // other stuff
  }

}
Community
  • 1
  • 1
udalmik
  • 7,838
  • 26
  • 40
  • see i have class for example print public class print{ public void static main(String args[]) { System.out.println("print"); } } see this code can we used any where to print so can we call it as reusable? –  Feb 22 '13 at 07:20
-1

yes java beans are piece of reusable codes,this means that you can reuse it any where. Following is an example.

package customer;
import java.io.*;
import java.util.*;
import java.sql.*;

public class Customer implements Serializable
{

        private String custID;
        private String custName;
        private int qty;
        private float price;
        private float total;
        private int storeCust;

        public String getCustID() {
            return custID;
        }

        public void setCustID(String custID) {
            this.custID = custID;
        }

        public String getCustName() {
            return custName;
        }

        public void setCustName(String custName) {
            this.custName = custName;
        }

        public int getQty() {
            return qty;
        }

        public void setQty(int qty) {
            this.qty = qty;
        }

        public float getPrice() {
            return price;
        }

        public void setPrice(float price) {
            this.price = price;
        }

        public float getTotal() {
            return total;
        }

        public void setTotal(float total) {
            this.total = total;
        }

        public int setStoreCust() 
        {
            try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/usermaster","admin","password");
            PreparedStatement pstmt=null;
            String query=null;
            query="insert into customer values(?,?,?,?,?)";
            pstmt=con.prepareStatement(query);
            pstmt.setString(1,custID);
            pstmt.setString(2,custName);
            pstmt.setInt(3,qty);
            pstmt.setFloat(4,price);
            pstmt.setFloat(5,total);
            int i=pstmt.executeUpdate();

            this.storeCust=i;
            }
            catch(Exception e)
            {

            }
            return storeCust;
        }
}

and this is a jsp page

<%@ page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.util.*" %>
<%@ page import="customer.Customer" %>
<html>
    <head>
        <title>JSP and JavaBean</title>

        <%-- create an instance of Customer class --%>
        <jsp:useBean id="cObj" scope="request" class="customer.Customer">

        <%-- Set the value of attribute such as CustID --%>
        <jsp:setProperty name="cObj" property="*" />
        </jsp:useBean>

    </head>
<body>

<%
            int x=cObj.setStoreCust();

            if(x>=1)
            {
        %>
                <jsp:forward page="Success.jsp" />
        <%

            }
            else
            {
        %>
                <jsp:forward page="Failure.jsp" />
        <%

            }

        %>

when you run this jsp page it will ask for cutomer id,quantity,total etc and after you submit it then it will insert it into database. For example you want to enter 1000 records so in this point you are not creating 1000 times java file,just you create once and then everything will be done by bean.

Following are some rules of javabeans,keep it in mind

1.javabean must contain a constructor that does not accept any arguements. 2.javabean cant declare any public instance variables; 3.javabeans must contain get and set methods for all of the properties that need to be accessed by JSPs.