Encapsulation In Java With Realtime Example

Introduction to Encapsulation in Java: In this tutorial, I am going to discuss about the "real-time example of encapsulation in java" hope it will helpful for you.

Encapsulation: [A mechanism which is to hide information (Data or Implementation)] Here, the capsule means it is just a container or we can say that a structure that enclose a body part (function or class).

Encapsulation in java with realtime example
Img: Wikipedia



Encapsulation is a process of binding data member (like variables, properties) and member function (like methods) into a single unit. If we talk about class and function it is the best example of encapsulation in java.

In other words, encapsulation is the process of hiding the internal details of an object. We can achieve encapsulation by hiding details using the access modifier (Public, Private, Protected, Default).


class Students          //No matter there is union or struct
{
   
public double totalMarks;  //data, variable or attribute
   public double MarksScored; 

   Public double GetPercentageMarks()      //operation
   {
       double Percentage =(MarksScored /totalMarks) * 100;
       return Percentage;
   }

}

Students OOpsStd = new Students(); 

In the above code we have encapsulated totalMarks, MarksScored and Method GetPercentMarks. While creating a "OOpsStd" object, the implementation of  GetPercentMarks will not be shown.

--------------------------------------------------------------------------------------------------------------------------

A function is also Example of Encapsulation


void add()
{
    int a = 4;
    int b = 5;      //data, variable or attribute
    int  c;

    c =  a + b;       //operation

    cout << "Addtion of 2 no is: " << c;

}   

--------------------------------------------------------------------------------------------------------------


Why we use Encapsulation in java

1) We can control the way of data accessibility.
2) Later on, you can modify the code at your end.
3) Encapsulation in java helps us to achieve loosely couple.
4) The main goal of Encapsulation is to achieve simplicity in our application.
5) Encapsulation in Java allows you to change one part of the code without affecting another part line of code.

Encapsulation in java with real-time example:

Encapsulation in java with realtime example
Img:Wikipedia


Encapsulation play a major role by developing the application the literal meaning of abstraction or the simplest mean of show the operational part or providing the operational part to the use is abstraction and encapsulation is hiding the complexity from the user is set to be the encapsulation 

                                                      or

We can say if there is a encapsulation there will we abstraction if we place an order for mobile to X company customer or  user is only consort for operation the mobile like brightness , volume ,SMS,call,power off he is not caller of the internal component of the mobile like electrical part of handset, how touch screen made he doesn't know that's encapsulation. He only knows functioning part of mobile or operational part of mobile this call abstraction.





Read More

Repeater in asp.net | use of repeater control


A repeater in asp.net: In this tutorial, I am going to discuss about the repeater control in asp.net c#, we will also discuss about crud operation with "repeater control" in asp.net.

Why "Repeater in asp.net" 
In Repeater control, the Data records to be displayed depends upon the Templates specified and the only HTML generated is the due to the Templates.


Repeater in asp.net,repeater control
Repeater in asp.net 

The actual use of  repeater control is to display a list of data from the sql server ,we can also use many more data source to display the record on repeater in asp.net.

Here are the some list of templates which is used with repeater control 

1.Item Template
2.Header Template
3.Footer Template
4.Separator Template
5.Alternating Item Template 

#Step 1: Now, I am going to show you how you can implement repeater control in asp.net .  First, you have to create a table to store data of  repeater control

create database Repeater_control
use Repeater_control

create table repeaterinaspnet
(
pid int identity primary key,
Name varchar(50),
Price varchar(50),
Pic varchar(50)
)



create proc usp_product_get
as
 begin
select * from repeaterinaspnet
end

create proc sp_product_insert
@Name varchar(50),
@Price varchar(50),
@Pic varchar(50)
as
 begin
insert into repeaterinaspnet(Name,Price,Pic)values(@Name,@Price,@Pic)
end

create proc usp_product_delete
@pid int,
@pic varchar(1000) output
as
 begin
  select @pic=pic from repeaterinaspnet
delete from  repeaterinaspnet where pid=@pid
end

ALTER proc sp_product_update
@pid int,
@Name varchar(50),
@Price varchar(50),
@Pic varchar(50)
as
 begin
  update repeaterinaspnet set Name=@Name,Price=@Price, @Pic=pic where pid=@pid

end

#Step 2: Now add a connection in web..config file

<configuration>
<connectionStrings>
  <add connectionString ="data source=SANJAY\SQL2012; initial catalog=DBUPLOAD; integrated security=true;" name ="reapterconnection"/>
</connectionStrings>
    <system.web>
      <compilation debug="true" targetFramework="4.5.2" />
      <httpRuntime targetFramework="4.5.2" />
    </system.web>

</configuration>

#Step 3: Add a asp.net c# webform , in my case my webform name is repeater_control _in_aspnet.aspx.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="repeater_in_aspnet.aspx.cs" Inherits="repeater_in_aspnet" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>Name :</td>
                    <td>
                        <asp:TextBox ID="txt_name" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td>Price :</td>
                    <td>
                        <asp:TextBox ID="txt_price" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td>Pic :</td>
                    <td>
                        <asp:FileUpload ID="fupic" runat="server"></asp:FileUpload></td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <asp:Button ID="btn_save" runat="server" Text="Save" OnClick="btn_save_Click" /></td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <asp:Repeater ID="RepDetails" runat="server" OnItemCommand="RepDetails_ItemCommand">
                            <HeaderTemplate>
                                <table style="border: 1px solid #df5015; width: 500px" cellpadding="0">
                                    <tr style="background-color: #df5015; color: White">
                                        <td>
                                            <b>Name</b>
                                        </td>
                                        <td>
                                            <b>Price</b>
                                        </td>
                                        <td>
                                            <b>Pic</b>
                                        </td>
                                        <td></td>
                                        <td></td>
                                    </tr>
                            </HeaderTemplate>
                            <ItemTemplate>
                                <tr style="background-color: #EBEFF0">
                                    <td>
                                        <%#Eval("Name"%>
                                    </td>
                                    <td>
                                        <%#Eval("Price"%>
                                    </td>
                                    <td>
                                        <asp:Image ID="Image1" runat="server" Width="70px" Height="50px" ImageUrl='<%#Eval("Pic","~/repeaterdata/{0}"%>' />
                                    </td>
                                    <td>
                                        <asp:LinkButton ID="lnkbtnedit" runat="server" Text="Edit" CommandArgument='<%#Eval("PID"%>' CommandName="EDT"></asp:LinkButton>
                                    </td>
                                    <td>
                                        <asp:LinkButton ID="lnkbtndelete" runat="server" Text="Delete" CommandArgument='<%#Eval("PID"%>' CommandName="DLT"></asp:LinkButton>
                                    </td>
                                </tr>
                            </ItemTemplate>
                            <FooterTemplate>
                                </table>
                            </FooterTemplate>
                        </asp:Repeater>

                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>


#Step 4: Come to the repeater_control _in_aspnet.aspx.cs page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Web.UI.HtmlControls;

public partial class repeater_in_aspnet : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["reapterconnection"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Fill_Reapter();
        }
    }
    //Bind the repeater control
    public void Fill_Reapter()
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("usp_product_get", con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            RepDetails.DataSource = ds;
            RepDetails.DataBind();
        }
        else
        {
            RepDetails.DataSource = null;
            RepDetails.DataBind();
        }

        con.Close();
    }
     //Button to insert data in repeater control
    protected void btn_save_Click(object sender, EventArgs e)
    {
        string FN = "";
        if (btn_save.Text == "Save")
        {
            FN = DateTime.Now.Ticks.ToString() + Path.GetFileName(fupic.PostedFile.FileName);
            fupic.SaveAs(Server.MapPath("repeaterdata" + "\\" + FN));
            con.Open();
            SqlCommand cmd = new SqlCommand("sp_product_insert", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Name", txt_name.Text);
            cmd.Parameters.AddWithValue("@Price", txt_price.Text);
            cmd.Parameters.AddWithValue("@Pic", FN);
            cmd.ExecuteNonQuery();
            con.Close();
        }
        else if (btn_save.Text == "Update")
        {
            FN = Path.GetFileName(fupic.PostedFile.FileName);
            con.Open();
            SqlCommand cmd = new SqlCommand("sp_product_update", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@pid", ViewState["PID"]);
            cmd.Parameters.AddWithValue("@Name", txt_name.Text);
            cmd.Parameters.AddWithValue("@Price", txt_price.Text);
            if (FN != "")
            {
                FN = DateTime.Now.Ticks.ToString() + Path.GetFileName(fupic.PostedFile.FileName);
                cmd.Parameters.AddWithValue("@Pic", FN);
                File.Delete(Server.MapPath("repeaterdata" + "\\" + ViewState["PIC"]));
                fupic.SaveAs(Server.MapPath("repeaterdata" + "\\" + FN));
            }
            else
            {
                cmd.Parameters.AddWithValue("@Pic", ViewState["PIC"]);
            }
            cmd.ExecuteNonQuery();
            con.Close();
        }
        Fill_Reapter();
    }

     //Edit and update event for the repeater control
    protected void RepDetails_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        int PID = int.Parse(e.CommandArgument.ToString());
        if (e.CommandName == "EDT" && PID > 0)
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("usp_product_get", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                DataView dv = new DataView(ds.Tables[0]);
                dv.RowFilter = "PID=" + PID;
                DataTable dt = new DataTable();
                dt = dv.ToTable();
                txt_name.Text = dt.Rows[0]["Name"].ToString();
                txt_price.Text = dt.Rows[0]["Price"].ToString();
                ViewState["PIC"] = dt.Rows[0]["Pic"].ToString();
                ViewState["PID"] = PID;
                btn_save.Text = "Update";
            }
        }
        else if (e.CommandName == "DLT" && PID > 0)
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("usp_product_delete", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@pid", PID);
            SqlParameter param = cmd.Parameters.Add("@pic"SqlDbType.VarChar, 200);
            param.Direction = ParameterDirection.Output;
            cmd.ExecuteNonQuery();
            con.Close();
            string FF = cmd.Parameters["@pic"].Value.ToString();
            File.Delete(Server.MapPath("repeaterdata" + "\\" + FF));
            Fill_Reapter();
        }
    }
}




Read More