Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Jsp Use Constructor in JSP

Related Tutorials


 
 

Share on Google+Share on Google+

Use Constructor in JSP

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

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

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: August 5, 2008

Related Tutorials

Discuss: Use Constructor in JSP  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com