Use Constructor in JSP

Constructors are used to initialize the object. They are just like method declaration but they do not return value.

Use Constructor in JSP

Use Constructor in JSP

     

This section illustrates you how to use constructors in jsp.

Constructors are used to initialize the object. They are just like method declaration but they do not return value. Constructors are defined by their class name. Here is an example which explains you to use constructors in jsp.

Here is the code of jspConstructor.jsp

<html>
<head>
<title>Use Constructor in jsp</title>
<body>
<H1>Using Constructor in jsp</H1>
<%!
javax.servlet.jsp.JspWriter con;

class X
{
int side;
int area;
int perimeter;
X() throws java.io.IOException 
{
con.println("<b>Area and Perimeter of Square</b><br>");
}
}
class Y extends X
{
Y(int side) throws java.io.IOException 
{
super();
area=side*side;
perimeter=4*side;
con.println("Area of Square=");
con.println(area);
con.println("<BR>");
con.println("Perimeter of Square=");
con.println(perimeter);
con.println("<BR>");
}
}
%> 
<%
con = out; 
Y obj = new Y(4);
%>
</body>
</html>

In the above example, we are calculating the Area and Perimeter of Square. For this, class X is defined and variables are initialized here. It invokes its constructor X(). Another class Y is defined which extends the class X and invokes a constructor Y(int side). This constructor calls the super class X by super() and define area and perimeter. Create the object of class Y and pass the value 4. It will take side=4 and calculate the result by area=side*side and perimeter=4*side.

Here is the output.

Download Source Code