Friday, July 2, 2010

Java's Constructor with Arguments

You can pass arguments to constructors but just like any other method, arguments for constructor must be one:one ratio and of the same data type.

Below are the two files where one passes arguments to another file containing the constructor.

[+/-] show/hide

import javax.swing.*;
class TestExpandedConstructorv2 {
public static void main (String args[]){

String sitenum = JOptionPane.showInputDialog(" Input site number:");
String UsageFee = JOptionPane.showInputDialog(" Input usage fee:");
String mgrname = JOptionPane.showInputDialog(" Input manager's name:");
int a = Integer.parseInt(sitenum);
double b =Double.parseDouble(UsageFee);

//calling a class with constructor and arguments
EventSiteConstructorv2 oneSite = new EventSiteConstructorv2(a,b,mgrname);

System.out.println("Name :"+oneSite.getManagerName());
System.out.println("Site Number: "+oneSite.getSiteNumber());
System.out.println("Usage Fee:"+oneSite.getUsageFee());

public class EventSiteConstructorv2 {

private int siteNumber;
private double usageFee;
private String managerName;

EventSiteConstructorv2(int x, double y, String z){

public int getSiteNumber()
{ return siteNumber;}
public void setSiteNumber(int n)
{ siteNumber=n;}

public void setUsageFee(double amt)
{ usageFee=amt;}

public double getUsageFee()
{ return usageFee;}
public String getManagerName()
{ return managerName;}

public void setManagerName(String name)
{ managerName=name;}


No comments: