Constructor Overloading

I am making a program that takes in some information from the user. As an example, the program takes in home phone number and mobile phone number.
I'd like to give the user the option of just not entering in one of those. I could do this with overloading the constructor. Would this be the best way to do this?
It seems to get messy since I have a lot of options that the user could leave out and then obviously need a constructor for each. I would have about four constructors. Is this bad practice? If so, what would be the best way to do this?

Since phone numbers are Strings, you could just use one constructor and pass empty strings if necessary,.

Similar Messages

  • Unable to implement Constructor Overloading in an inherited class. Plz Help

    Please do compile the program in in order to notice the error.
    class EmpDet
    int id,age;
    String name;
    String gender;
      EmpDet(int id1,String name1,int age1,String gender1)
        this.id = id1;
        this.name= name1;
        this.age= age1;
        this.gender = gender1;
       void Id_Name()
       System.out.println("EmpId : "+id+" and Name : "+name);
       void Gender_Age()
        System.out.println("Employee is a "+gender+" and is "+age+" years old.");
      class Employee extends EmpDet
           String locality;
        Employee(int a,String b,int c,String d)
             super(a,b,c,d);
        Employee(String locality1)// Constructor overloading. My problem.
             this.locality = locality1;
      void locality()
        System.out.println("The employee resides at "+locality);
       void DiplayStmt()
            System.out.println("DISPLAYING EMPLOYEE DETAILS..");
            System.out.println("******************************");
       public static void main (String[] args)
        Employee det = new Employee(010,"John",32,"M");
        Employee addr = new Employee("Tambaram");
        addr.DiplayStmt();
        det.Id_Name();
        det.Gender_Age();
        addr.locality();
      }

    Hey Thanks.. I guess what you said makes sense.
    I was fiding it hard to agree that there needs to be a match between the Constructors of the Base Class and the Sub Class. I altered the program by adding a constructor in the Base class and using the super(0 function in the Sub class and that seems to work..
    class EmpDet
    int id,age;
    String name;
    String gender;
    EmpDet(int id1,String name1,int age1,String gender1)
         this.id = id1;
    this.name= name1;
    this.age= age1;
    this.gender = gender1;
    EmpDet(String addr)
         System.out.println("Address is implemented in SubClass");
    void Id_Name()
    System.out.println("EmpId : "+id+" and Name : "+name);
    void Gender_Age()
    System.out.println("Employee is a "+gender+" and is "+age+" years old.");
    class Employee extends EmpDet
         String locality;
    Employee(int a,String b,int c,String d)
         super(a,b,c,d);
    Employee(String locality1) // Constructor Overloading
         super(locality1);
         this.locality = locality1;
    void locality()
    System.out.println("The employee resides at "+locality);
    void DiplayStmt()
         System.out.println("DISPLAYING EMPLOYEE DETAILS..");
         System.out.println("******************************");
    public static void main (String[] args)
    Employee det = new Employee(010,"John",32,"M");
    Employee addr = new Employee("Tambaram");
    addr.DiplayStmt();
    det.Id_Name();
    det.Gender_Age();
    addr.locality();
    Message was edited by:
    3402102

  • Is this constructor overloading??

    class A
    A(){
    System.out.println("A is instantiated");
    public void A(){
    System.out.println("inside the method A of class A");
    class B extends A
    B(){
    System.out.println("B is instantiated");
    public void B(){
    System.out.println("inside the method B of class B");
    public static void main(String[] args) {
    A a = new A();
    a.A();
    B b = new B();
    b.A();
    b.B();     
    since i hav given same names to constructor and method in class A and also in class B....i hav doubt whether is constructor overloading or not?

    Try compiling this code:
    class ObjectOne {
        ObjectOne() {}
        ObjectOne(int n) {
            System.out.println(n);
    class ObjectTwo extends ObjectOne {
        public static void main(String[] args) {
            ObjectTwo obj = new ObjectTwo(9);
    }The very first line of any constructor is a call to super. Even if you do not type it, that line is explicitly inserted by the compiler.
    So this:
    class Foo extends Bar {
        Foo() {
            System.out.println("Foo");
    }becomes
    class Foo extends Bar {
        Foo() {
            super();  // explicit call to super
            System.out.println("Foo");
    }

  • Java constructor overload error

    I just tried a simple java program and it works on Linux but fails on Mac. Here is the code:
    package TestProject;
    public class Main {
               * @param args
              public static void main(String[] args) {
      // TODO Auto-generated method stub
                  int x =5;
                  int y = 6;
                  double a=5.0;
                  double b=6.0;
                  testout to1 = new testout(x,y);
                  testout to2 = new testout(a, b);
                  System.out.println(to1.getIntResult());
                  System.out.println(to2.getDoubleResult());
    package TestProject;
    public class testout {
        private int a=0, b=0;
        private double c=0.0, d=0.0;
        public void testout(int x, int y)
            a = x;
            b = y;
        public testout(double x, double y)
            c = x;
            d = y;
        public double getDoubleResult()
            return c + d;
        public int getIntResult()
            return a + b;
    As you see I have a constructor to pass either two ints or two doubles. When I run the program on Linux I get the expected result. When I run on Mac, the getIntResult returns zero. I debugged the program and the int constructor is using the double instead. I verified on both netbeans and eclipse.
    Looks like a bug but maybe I am doing something stupid.....

    Not being a Java developer, only have taken one semester of Java, and not having slept in a Holiday Inn recently, I couldn't tell you if it is a bug or not, but since an int can be freely cast to a double, maybe the Mac OS X JRE is finding the double, double constructor and saying to itself, "self, I can make those ints into doubles, so let's just use this double, double signature. la la la alaalla lla alllaaaaalllaa la al."
    If you can find documentation in the Java implementation that directs you use the best constructor vice any appropriate constructor, file a bug report.
    I would imagine you should always use the best match, not just one that works.

  • Issue with creating array of custom data type - WebLogic Integration

    Hi,
    We are doing WebLogic integration with Siebel for which from Siebel side we have generated java wrapper class which has all the methods, input\outputs defined and in\out params are serialized along with get\set methods. Following are the details of the input\output args.
    Account_EMRIO.java
    public class Account_EMRIO implements Serializable, Cloneable, SiebelHierarchy {
    protected String fIntObjectFormat = null;
    protected String fMessageType = "Integration Object";
    protected String fMessageId = null;
    protected String fIntObjectName = "Account_EMR";
    protected String fOutputIntObjectName = "Account_EMR";
    protected ArrayList <AccountIC> fintObjInst = null;
    Above class also includes constructors\overloaded constructor\getters\setters
    public AccountIC getfintObjInst() {    
    if(fintObjInst != null) {
    return (AccountIC)fintObjInst.clone();
    }else{
    return null;
    public void setfintObjInst(AccountIC val) {
    if(val != null) {
    if(fintObjInst == null) { 
    fintObjInst = new ArrayList<AccountIC>();
    fintObjInst.add(val);
    For the nested user defined data type AccountIC, it is defined in another java class as below
    AccountIC.java
    public class AccountIC implements Serializable, Cloneable, SiebelHierarchy {
    protected String fname = null;
    protected String fParent_Account_Id= null;
    protected String fPrimary_Organization = null;
    With the above, I was able to get all the AccountIC in the wsdl correctly and using this I was able to set the input param in the client
    WSDL:
    <xs:complexType name="accountEMRIO">
    <xs:sequence>
    <xs:element name="fIntObjectFormat" type="xs:string" minOccurs="0"/>
    <xs:element name="fIntObjectName" type="xs:string" minOccurs="0"/>
    <xs:element name="fMessageId" type="xs:string" minOccurs="0"/>
    <xs:element name="fMessageType" type="xs:string" minOccurs="0"/>
    <xs:element name="fOutputIntObjectName" type="xs:string" minOccurs="0"/>
    <xs:element name="fintObjInst" type="tns:accountIC" minOccurs="0"/>
    </xs:sequence>
    <xs:complexType name="accountIC">
    <xs:sequence>
    <xs:element name="fName" type="xs:string" minOccurs="0"/>
    <xs:element name="fParent_Account_Id" type="xs:string" minOccurs="0"/>
    <xs:element name="fPrimary_Organization" type="xs:string" minOccurs="0"/>
    minOccurs="0"/>
    </xs:sequence>
    </xs:complexType>
    Now, I wanted to make slight difference in getter method of class Account_EMRIO method getfintObjInst so that an array of AccountIC is retured as output.
    public ArrayList<AccountIC> getfintObjInst() {    
    if(fintObjInst != null) {
    return (ArrayList<AccountIC>)fintObjInst.clone();
    }else{
    return null;
    With the above change, once the wsdl is generated, I am no longer getting fintObjInst field for AccountIC due to which I am unable to get the array list of accountIC
    WSDL:
    <xs:complexType name="accountEMRIO">
    <xs:sequence>
    <xs:element name="fIntObjectFormat" type="xs:string" minOccurs="0"/>
    <xs:element name="fIntObjectName" type="xs:string" minOccurs="0"/>
    <xs:element name="fMessageId" type="xs:string" minOccurs="0"/>
    <xs:element name="fMessageType" type="xs:string" minOccurs="0"/>
    <xs:element name="fOutputIntObjectName" type="xs:string" minOccurs="0"/>
    </xs:sequence>
    </xs:complexType>
    The issue that I am facing here is, we have a custom data type(AccountIC) which has several fields in it. In the output I need a array of AccountIC. In the java bean, when this type was defined as
    protected ArrayList <AccountIC> fintObjInst = null; I was unable to get a array of AccountIC. this gets complicated as inside a AccountIC there is array of contacts as well and all the time I am getting just the first records and not a array.
    To summarize: How to get xsd:list or maxoccurs property for a field in WSDL for the user defined\custom datatype?
    Can someone help me with this.
    Thanks,
    Sudha.

    can someone help with this??

  • Consuming a jms queue from a multithread application

    Hi
    Thank you for reading my post.
    I have an application which shuld consume message of a queue.
    my application is multithread and what i want to know is:
    - How i can ask queue to remove a message after my thread finished its work with the message, by this way i can ensure that if my thread face an exception after it read the message my message will not lose.
    - As it is multithread application, How i can ensure that a message is not delivered to two or more thread? is there any way to consume the messages in a synchronized way?
    Will synchronized access restrict the performance?
    Thanks

    This is running in a J2DK environment. For my thread pool, I just copied one from a Sun tutorial on multi-threading then modified it. I creaed a seperate package with three classes. Here is my thread pooling package. I basically use a Vector to hold threads when they are not working. And you can set a limit as to the max number of active threads.
    package threadpooling;
    * @author cferris
    *  This class is simple to wrap the runnable
    *  thread for the worker thread around other
    *  needed parameters like salon id and source.
    public class TaskWrapper {
      // Define the needed instance fields.
      public  Runnable taskAtHand = null;
      public  String taskType = "";
        // Overloaded constructor.
        public TaskWrapper(Runnable task) {
          // Just set the runnable
          taskAtHand = task;
          taskType = "WorkerThread";
        }  // of overloaded contructor
        // Overloaded constructor.
        public TaskWrapper(Runnable task, String taskType) {
          // Just set the instance fields
          taskAtHand = task;
          this.taskType = taskType;
        }  // of overloaded contructor
    package threadpooling;
    * @author cferris
    *  This class is for tracking the number of
    *  active threads so we don't go over the set
    *  limit. This class basically synchronizes
    *  the methods that update the active thread
    *  counter.
    import java.util.*;
    public class ThreadPool {
      // Define the instance fields.
      //   First define instance fields for the
      //   management of the thread pools - pm.
      protected Vector poolOfThreads = new Vector();
      private  static LinkedList taskQueue = new LinkedList();
      private  static int poolSize = 0;
      private  static boolean pmAvailable = true;
      private  static boolean daemon = false;
      public   static boolean shutDown = false;
      //   Instance field for the management of
      //   the threads - tm.
      private  static int activeThreads = 0;
      private  static int maxReached = 0;
      private  static int numTimesReached = 0;
      private  static boolean tmAvailable = true;
      // Define constants
      private  static final int MAX_LIMIT_DEFAULT = 32;
        // The constructor.
        public ThreadPool() {
          this(MAX_LIMIT_DEFAULT, false);
        }  // of constructor
        // Overload the constructor with max number of active jobs.
        public ThreadPool(int poolSize, boolean daemon) {
          this.poolSize = poolSize;
          this.daemon = daemon;
          poolOfThreads = new Vector();
          taskQueue = new LinkedList();
          salonTracker = new Vector();
          // Load up and initialize the threads.
          for (int i=0; i < poolSize; i++) {
              Thread thread = new WorkerThread(this, i);
              thread.setDaemon(daemon);
              thread.start();
              poolOfThreads.add(thread);
        }  // of overloaded constructor
        // Overload this method to allow just the runnable task.
        public void assignWork(Runnable work) {
          // Create the wrapper
          TaskWrapper wrapper = new TaskWrapper(work, "A task");
          assignWork(wrapper);
        }  // of overloaded assignWork
        // Push a unit of work (work thread) on the the worker thread.
        public synchronized void assignWork(TaskWrapper work) {
          // First increament the active thread count.
          increment();
          // Wait until we can access the linked list 
          try {
              if (!pmAvailable)
                  wait();
          } catch(InterruptedException e) { }
          pmAvailable = false;
          notifyAll();
          taskQueue.addLast(work);
          pmAvailable = true;
          notifyAll();
        }  // of assignWork
        // Get the next unit of work (work thread).
        public synchronized TaskWrapper getNextWorkAssignment()  {
          // Wait until we can access the linked list 
          try {
              if (!pmAvailable)
                  wait();
          } catch(InterruptedException e) { }
          pmAvailable = false;
          notifyAll();
          TaskWrapper nextTask;
          if (!taskQueue.isEmpty())
              nextTask = (TaskWrapper)taskQueue.removeFirst();
          else
              nextTask = null;
          pmAvailable = true;
          notifyAll();    
          return nextTask;
        }  // of getNextWorkAssignment
        // Return the number of tasks waiting on the work queue.
        public synchronized int workWaiting()  {
          // Wait until we can access the linked list 
          try {
              if (!pmAvailable)
                  wait();
          } catch(InterruptedException e) { }
          pmAvailable = false;
          notifyAll();
          int qSize = taskQueue.size();
          pmAvailable = true;
          notifyAll();    
          return qSize;
        }  // of workWaiting
        // Wait until all the tasks have been completed.
        public void waitForCompletion() {
          int prev = 0;
          // Continue checking untill all the threads have
          // completed and been removed.
          while(!poolOfThreads.isEmpty()) {
             // Lets record the difference
             if (poolOfThreads.size() != prev) {
                 System.out.println("waiting for " + poolOfThreads.size() + " to complete");
                 prev = poolOfThreads.size();
             // Loop through the thread pool and check each thread.         
             for (int t = 0; t < poolOfThreads.size(); t++)
                  if (!((WorkerThread)poolOfThreads.get(t)).working)
                      // This thead is done so remove it.
                      poolOfThreads.remove(t);
          }  // of while
        } // waitForCompletion
        // Set the max number of allow threads.
        public synchronized void setPoolSize(int newLimit) {
          // just set the limit.
          // Check if available
          while (!tmAvailable) {
             try {
               wait();
             catch(InterruptedException ie) {
               System.exit(5);
          // Ok, lock the object while we update it.
          tmAvailable = false;
          notifyAll();
          poolSize = newLimit;
          // Reset the max counters/trackers too
          maxReached = 0;
          numTimesReached = 0;
          // Create additional threads in the pool if needed
          if (poolSize > poolOfThreads.size())
              // Load up and initialize the threads.
              for (int i = poolOfThreads.size(); i < poolSize; i++) {
                  Thread thread = new WorkerThread(this, i);
                  thread.start();
                  poolOfThreads.add(thread);
          // Done, now release the object.
          tmAvailable = true;
          notifyAll();       
        }  // of setPoolSize.
        // The method to increment thread counter.
        private synchronized void increment() {
          // Check if available
          while (!tmAvailable) {
             try {
               wait();
             catch(InterruptedException ie) {
               // logger.fatal("Synchronized error in ThreadPool "); 
               // logger.fatal("Error message is: " + ie.getMessage());
               System.exit(5);
          // Ok, lock the object while we update it.
          tmAvailable = false;
          notifyAll();
          activeThreads++;
          // Check if this is the highest number of threads
          // that has been active, if not then set so.
          if (activeThreads > maxReached)
              maxReached = activeThreads;
          if (activeThreads == poolSize)
              numTimesReached++;
          // Done, now release the object.
          tmAvailable = true;
          notifyAll(); 
        }  // of increment
        // The method to increment thread counter.
        public synchronized void decrement() {
          // Check if available
          while (!tmAvailable) {
             try {
               wait();
             catch(InterruptedException ie) {
               // logger.fatal("Synchronized error in ThreadPool "); 
               // logger.fatal("Error message is: " + ie.getMessage());
               System.exit(5);
          // Ok, lock the object while we update it.
          tmAvailable = false;
          notifyAll();
          activeThreads--;
          // Done, now release the object.
          tmAvailable = true;
          notifyAll(); 
        }  // of decrement
        // A method to determine if the maximum number of active
        // threads has been reached.
        public synchronized boolean limitNotReached() {
          boolean limit = false;
          // Check if available
          while (!tmAvailable) {
             try {
               wait();
             catch(InterruptedException ie) {
               // logger.fatal("Synchronized error in ThreadPool."); 
               // logger.fatal("Error message is: " + ie.getMessage());
               System.exit(5);
          // Ok, lock the object while we update it.
          tmAvailable = false;
          notifyAll();
          if (activeThreads < poolSize)
             limit = true;
          // Done, now release the object.
          tmAvailable = true;
          notifyAll();
          return limit;
        }  // of limitNotReached
        // A method to return the number of active threads.
        public synchronized int currentNum() {
          // Check if available
          while (!tmAvailable) {
             try {
               wait();
             catch(InterruptedException ie) {
               // logger.fatal("Synchronized error in ThreadPool"); 
               // logger.fatal("Error message is: " + ie.getMessage());
               System.exit(5);
          // Ok, lock the object while we update it.
          tmAvailable = false;
          notifyAll();
          int numberOf = activeThreads;
          // Done, now release the object.
          tmAvailable = true;
          notifyAll();
          return numberOf;
        }  // of currentNum
    package threadpooling;
    * @author cferris
    *   This is the work thread that receives the
    *   taskes or unit of work that make up the
    *   thread pool.
    public class WorkerThread extends Thread {
      // Define need instance fields.
      public  boolean working = true;
      public  int id = 0;
      private int pauseFactor = 1;
      // The thread pool that this object belongs to.
      public ThreadPool owner;
      // Define the constructor for the seperate thread.
      public WorkerThread(ThreadPool pooler, int id)  {
        owner = pooler;
        this.id = id;
      }  // of contructor
      //  Wait for work or for system shutdown.
      public void run() {
        // Define the work object. 
        TaskWrapper unitOfWork = null;
        // Wait for work or until system is shutting down.
        do {
           unitOfWork = owner.getNextWorkAssignment();
           if (unitOfWork != null) {
               // First set name and then add salon to watch list.
               String taskName = unitOfWork.taskType + "-" + id;
               setName(taskName);
            // System.out.println("Starting thread - " + getName());
               unitOfWork.taskAtHand.run();
               // Done, now adjust tracker and reset the pause factor.
               owner.decrement();
               pauseFactor = 1;
           else {
               // No work so pause a bit
               try {
                   sleep(150 * pauseFactor);
               } catch (InterruptedException e) { }
               // If consecutively pausing because of no work then
               // increase the pause time up to a point.
               if (pauseFactor < 49)
                   pauseFactor++;
        } while (!owner.shutDown);
        // Set indicator this thread in the pool is done.
        working = false; 
      }  // of run
    }To use the thread pool just create a static instance of the ThreadPool in your main class
      private  static ThreadPool threadPool = new ThreadPool(getMaxThreads(), useDaemon());Then to launch a new thread use this.
        if (runOnSeperateThread()) {  
            WriteTransThread task = new WriteTransThread(messasge);
            // Add to the thread pool.
            threadPool.assignWork(new TaskWrapper(task, "my thread"));
      private boolean runOnSeperateThread() {
        // First check if mutli threading is turned on
        // and if there are open threads.
        if (multiThreadingOn && threadPool.limitNotReached())
            // Yes, there are open threads.
            return true;
        // Check if we can wait for an open thread.
        if (!multiThreadingOn || !waitForOpenThread)
            // No multi threading or waiting allowed.
            return false;
        // OK, wait for an open thread, wait for up
        // to 90 seconds.
        int j = 0;
        do {
            try {
                // Wait 1/2 a second.
                Thread.sleep(500);
            } catch(InterruptedException ignore) { };
            // Check again for an optn thread.
            if (threadPool.limitNotReached())
                // Ok to run on separate thread.
                return true;
            // Increament counter and wait again.
            j++;
        } while(j < 180);
        // If we got this far then we've waited long enough.
        logger.warn("Reached limit on waiting for an open thread in the pool");
        return false;
      }  // of runOnSeperateThreadThe WriteTransThread is a class that will extract the message body and write out its data to a table.
    Last, before you end your program make sure all the threads have competed by calling the following.
      //  If multi-threading is activated then this method will
      //  wait for them to complete before returning. The
      //  max wait time is 300 secs or 5 minutes.
      private void waitForThreadsToComplete(String message) {
        // First check for multi threading. 
        if (prop.useMultiThread() && (threadPool.currentNum() > 0)) {
            int limit = 0;       
            // Some threads are still active, wait
            logger.info("Waiting for threads to complete before " + message
                      + " current thread count is " + threadPool.currentNum());
            do {
               limit++;
               try {
                   Thread.sleep(500);  // Sleep 1/2 a sec.
               } catch(InterruptedException ie) { }  // Ignore the error for now.
               // Max waith is 300 sec or 5 min.
            } while ((threadPool.currentNum() > 0) && (limit < 600));
      }  // of waitForThreadsToComplete
     

  • ORA-06502 PL/SQL: numeric or... when exporting data

    I am getting this error message when I go to export data . I have a WHEN-BUTTON-PRESSED trigger on the Export button with the following code
    EXPORT_BLOCK(:SYSTEM.CURSOR_BLOCK);
    Why am I getting this error?
    Can anyone help.
    Thanks
    Nick

    Hi,
    You need to specify size for output varchar2 parameters. It looks like that may have been your intent, but the [constructor overload|http://download.oracle.com/docs/html/E15167_01/OracleParameterClass.htm#i1011428] you're using, the 3rd parameter is value, not size.
    Hope it helps,
    Greg

  • Help with class

    hello, I am having trouble with the following code I get the following errors. I have no idea how to fix this, if anyone could help I would greatly appriciate it.
    StudentAddress.java:12: StudentAddress(java.lang.String) is already defined in StudentAddress
    public StudentAddress(String city){
    ^
    StudentAddress.java:16: StudentAddress(java.lang.String) is already defined in StudentAddress
    public StudentAddress(String state){
    ^
    StudentAddress.java:24: StudentAddress(int) is already defined in StudentAddress
    public StudentAddress(int zipCode){
    //Data represents GPA/hours
    public class StudentAddress {
         //Declare Variables
         private String streetAddress, city, state;
         private int addressNumber, zipCode;
         public StudentAddress(String streetAddress){
              this.streetAddress = streetAddress;
         public StudentAddress(String city){
              this.city = city;     
         public StudentAddress(String state){
              this.state = state;
         public StudentAddress(int addressNumber){
              this.addressNumber = addressNumber;
         public StudentAddress(int zipCode){
              this.zipCode = zipCode;
              //this will return a string representation of this object so that
              //we can print it to the console easily
         public String toString(){
              return streetAddress + "\n" + "#" +addressNumber +"\n" + city + "," + state + zipCode;
    }

    when you create an instance of StudentAddress class, you will either pass a String or an int irrespective of whether it is city, state, streetAddress, addressNumber or zipCode. Suppose you create an instance of StudentAddress by passing a string, which constructor it will invoke? The JVM will get confused on which constructor to invoke since it has three constructors with the same String as the parameter type. What you have written is not 'Constructor Overloading'. Read some tutorial about constructors and constructor overloading and try coding.
    You can write this class as follows, Assuming that it will fulfill your requirement
    public class StudentAddress {
         //Declare Variables
         private String streetAddress, city, state;
         private int addressNumber, zipCode;
         public StudentAddress(String streetAddress,String city,String state,int addressNumber,int zipCode){
              this.streetAddress = streetAddress;
                                    this.city = city;
                                    this.state = state;
                                    this.addressNumber = addressNumber;
                                    this.zipCode = zipCode;
                                  //this will return a string representation of this object so that
              //we can print it to the console easily
         public String toString(){
              return streetAddress + "\n" + "#" +addressNumber +"\n" + city + "," + state + zipCode;
    }you can also try this website
    http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter03/constructors.html
    All the best. Have a Nice Day.

  • SSRS Custom Data Processing Extension Error

    I am using Custom Data Processing Extension to call a stored procedure. Iam getting following error when creating a dataset in report designer using the extension. I wrote the code in c#.
    could not update a list of fields for the query. verify that you can connect to the data source and that your query syntax is correct.(Details-Object reference not set to an instance of an object.)
    Here is my code
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;
    using System.Data;
    using System.Data.SqlClient;
    using Microsoft.ReportingServices.DataProcessing;
    using System.Diagnostics;
    using System.Text.RegularExpressions;
    namespace DataBaseDPE
    public class DBConnection:Microsoft.ReportingServices.DataProcessing.IDbConnectionExtension
    private string mconnstring;
    private string localname = "Database Connection";
    private ConnectionState mState = ConnectionState.Open;
    public DBConnection()
    Debug.WriteLine("DataSetConnection: Default Constructor");
    public DBConnection(string Dconnection)
    Debug.WriteLine("DataSetConnection Constructor overloaded with Connection String ");
    mconnstring = Dconnection;
    public Microsoft.ReportingServices.DataProcessing.IDbTransaction BeginTransaction()
    return (null);
    public string ConnectionString
    get
    return mconnstring;
    set
    mconnstring = value;
    public int ConnectionTimeout
    get
    return 0;
    public ConnectionState State
    get
    return mState;
    public void Open()
    mState = ConnectionState.Open;
    return;
    public void Close()
    mState = ConnectionState.Closed;
    return;
    public Microsoft.ReportingServices.DataProcessing.IDbCommand CreateCommand()
    return new DBCommand(this);
    public string LocalizedName
    get
    return localname;
    set
    localname = value;
    public void SetConfiguration(string configuration)
    try
    SqlConnection sqlconn = new SqlConnection("Data Source=localhost;Initial Catalog=AdventureWorks2000;Integrated Security=True;");
    catch (Exception e)
    throw new Exception(e.Message, null);
    public void Dispose()
    public string Impersonate
    { get; set; }
    public bool IntegratedSecurity
    { get; set; }
    public string Password
    { get; set; }
    public string UserName
    { get; set; }
    using System;
    using System.Collections.Generic;
    using System.Text;
    using Microsoft.ReportingServices.DataProcessing;
    using System.Data.SqlClient;
    namespace DataBaseDPE
    public class DBCommand : Microsoft.ReportingServices.DataProcessing.IDbCommand
    DBConnection mconnection = null;
    private string mCmdText;
    private int mCmdTimeOut = 30;
    private CommandType CmdType;
    public DBCommand()
    public DBCommand(string CmdText)
    mCmdText = CmdText;
    public DBCommand(DBConnection aConnection)
    mconnection = aConnection;
    public void Cancel()
    throw new NotImplementedException();
    public string CommandText
    get
    return mCmdText;
    set
    mCmdText = value;
    public int CommandTimeout
    get
    return mCmdTimeOut;
    set
    mCmdTimeOut = value;
    public CommandType CommandType
    get
    return CmdType;
    set
    CmdType = value;
    public IDataParameter CreateParameter()
    return (null);
    public class MySqlDataReader:Microsoft.ReportingServices.DataProcessing.IDataReader
    private System.Data.IDataReader sourceDataReader;
    private System.Data.DataTable dt;
    private System.Data.DataSet ds;
    private int fieldCount = 0;
    private string fieldName;
    private int fieldOrdinal;
    private Type fieldType;
    private object fieldValue;
    private int currentRow = 0;
    public MySqlDataReader(System.Data.IDataReader datareader)
    this.sourceDataReader = datareader;
    public MySqlDataReader(System.Data.DataTable dt)
    // TODO: Complete member initialization
    this.dt = dt;
    public MySqlDataReader(System.Data.DataSet ds)
    // TODO: Complete member initialization
    this.ds = ds;
    public int FieldCount
    get
    fieldCount = ds.Tables[0].Columns.Count;
    return fieldCount;
    public Type GetFieldType(int i)
    fieldType =
    ds.Tables[0].Columns[i].DataType;
    return fieldType;
    public string GetName(int i)
    fieldName = ds.Tables[0].Columns[i].ColumnName;
    return fieldName;
    public int GetOrdinal(string name)
    fieldOrdinal =
    ds.Tables[0].Columns[name].Ordinal;
    return fieldOrdinal;
    public object GetValue(int i)
    fieldValue =
    ds.Tables[0].Rows[this.currentRow][i];
    return fieldValue;
    public bool Read()
    currentRow++;
    if (currentRow >= ds.Tables[0].Rows.Count)
    return (false);
    else
    return (true);
    public void Dispose()
    public IDataReader ExecuteReader(CommandBehavior behavior)
    string query = "SampleSP";
    SqlConnection readerconn = new SqlConnection("Data Source=localhost;Initial Catalog=AdventureWorks2000;Integrated Security=SSPI");
    SqlCommand readercmd = new SqlCommand(query);
    readerconn.Open();
    readercmd = readerconn.CreateCommand();
    readercmd.CommandText = query;
    readercmd.CommandType = System.Data.CommandType.StoredProcedure;
    readerconn.Close();
    SqlDataAdapter adapter = new SqlDataAdapter(query,readerconn);
    readerconn.Open();
    adapter.SelectCommand = readercmd;
    System.Data.DataTable dt = new System.Data.DataTable();
    adapter.Fill(dt);
    System.Data.DataSet ds = new System.Data.DataSet();
    adapter.Fill(ds);
    return new MySqlDataReader(ds);
    public IDataParameterCollection Parameters
    get { return (null); }
    public IDbTransaction Transaction
    get
    return (null);
    set
    throw new NotImplementedException();
    public void Dispose()
    Please help me, Thanks in advance

    Sorry why do you need a Data Processing Extension for that? Cant you directly call the procedure
    from SSRS dataset? Whats the RDBMS which holds this procedure?
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Two methods with same name?

    hello,
    When a class has two or more methods with the same name but each method
    accepts unique parameters ..... what is this called? Overloading?
    Thanks,
    jd
    public class Test{
         public Test(){
              String bubby = sayHI("Jason");
              System.out.println(bubby);
         public String sayHI(){
              return "hi";
         public String sayHI(String name){
              return "hi " + name;
         public static void main(String[] args){
              getPrefs gp = new getPrefs();

    is this also called overloading when your doing it with the constructor?Yes, unequivocally.
    8.4.7 Overloading
    If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but different signatures, then the method name is said to be overloaded. This fact causes no difficulty and never of itself results in a compile-time error. There is no required relationship between the return types or between the throws clauses of two methods with the same name but different signatures.
    8.8.6 Constructor Overloading
    Overloading of constructors is identical in behavior to overloading of methods. The overloading is resolved at compile time by each class instance creation expression (�15.9).
    QED, &#167;

  • ArgumentNullException was Unhandled

    heey you guys,
    I have this error and I dont know How I can Solve it,
     this.timer1 = new System.Windows.Forms.Timer(this.components); // its about this line of code
    Does anybody know the solution to this error??
    thkns

    Create the Timer after the call to InitializeComponent():
    public Form1()
    InitializeComponent();
    this.timer1 = new System.Windows.Forms.Timer(this.components);
    Or use the constructor overload that doesn't take any argument:
    this.timer1 = new System.Windows.Forms.Timer();
    Please remember to close your threads by marking helpful posts as answer and please start a new thread if you have a new question.

  • Overloading constructor

    Hello
    I am having an adhoc problem with overloaded constructors:
    public class myFileRead {
    private int type;
    public myFileRead(File mp3, int nomenclature) {  //constructor 2
    type = nomenclature;
    myFileRead(File mp3);
    public myFileRead(File mp3) {  //constructor 1
    //code excised
    }All that I am tyring to do is set a member variable in constructor 2 and call constructor 1. My IDE is saying a missing ")" in constructor 2 call to constructor 1 at the parameter mp3. I have done this before. I have done a clean build. What am I missing here? Any enlightment welcomed.

    Hi Vanilla
    That was stupid about the type-ing the argument.
    However now it is demanding that the this(mp3) be
    e the first line. Yes. As Adeodatus mentioned. This is a requirement of the Java language.
    I dont see why. To ensure that all constructors complete before anything else happens, I guess. You probably rarely or never need to do something else first, and by knowing that you can't just invoke a constructor any old time, you eliminate one potential source of a lot of inconsistent or invalid or unpredicatable state.
    This is not
    extending any other object, except Object of course.Irrelevant.
    Are not all constructors equal? Yeah, I guess so. I don't see what that has to do with anything.
    Does this thereby
    y prevent the technique of using overloaded
    constructor to set a member value and then call some
    other constructor declaration?No. It just means that if you're going to call another c'tor, it must be the first thing that you do.

  • Can we use an overloaded constructor of a Java Bean with Session Tracking

    Hi Friends,
    If any one can solve my query.... It would be helpful.
    Query:
    I have a Java Bean with an overloaded constructor in it. I want to use the overloaded constructor in my JSP.
    1. One way of doing that is to use it directly in the "Scriptlets" (<% %>). But then I am not sure of the way to do session tracking. I think I can use the implicit objects like "session", "request" etc. but not sure of the approach or of the implementation method.
    2. Another way is through the directive <jsp: useBean>. But I cannot call an overloaded constructor with <jsp: useBean>. The only alternative way is to use the directive <jsp: useBean> where I have to write getter and setter methods in the Java Bean and use the <jsp: setProperty> and <jsp: getProperty> standard actions. Then with this approach I cannot use the overloaded constructor.
    Can any one suggest me the best approach to solve this problem ?
    Thanks and Regards,
    Gaive.

    My first reaction is that you can refactor your overloaded constructor into an init(arguments...) method. Instead of overloaded constructor, you can call that init method. This is the ideal solution if possible.
    As to the two choices you listed:
    1. This is OK, I believe. You can use scriplet to define the bean and put it into session scope of the pageContext. I am not sure exactly what you meant by session tracking; whatever you meant, it should be doable using HttpSessionAttributeListener and/or HttpSessionBindingListener.
    2. Agreed. There is no way that <jsp:useBean> can call a constructor that has non-empty arguments.
    Please tell me how it works for you.

  • Classes in JSP, Overloading of constructor (parametric constructor)

    Classes in JSP, Overloading of constructor (parametric constructor)
    I have created a Java class in JSP and created new objects, no problem.
    I have also manage to overload methods like
    writeOut() {}
    writeOut(String arg) {}
    writeOut(String arg, String arg2) {}
    But, i have a problem a parametric constructor (parametric constructor).
    Like if the class looks like this :
    class Test {
    public void Test() {}
    public void Test(String arg) {}
    public void Test(String arg, String arg2) {}
    I manage to compile this, but when i try to execute the parametric constructor by this code :
    <%Test objTest = new Test("value");%>
    I get 1 warning, and i do have a constructor that is like this :
    public void Test(String arg, String arg2) {....}
    C:\Program Files\Apache Tomcat 4.0\work\localhost\_\nils\slett-kode\test$jsp.java:114: Wrong number of arguments in constructor.
    Test objTest = new Test("hei","had");
    ^
    Note: C:\Program Files\Apache Tomcat 4.0\work\localhost\_\nils\slett-kode\test$jsp.java uses or overrides a deprecated API. Recompile with "-deprecation" for details.
    1 error, 1 warning
    Can anyone please help me, or tell me if i can have parametric constructor in JSP ?

    If it's still not working right, I'd suggest making sure that you don't have an old copy of the class file somewhere on your box that might be accessed instead of the one you really want it to. But yes, the following code executes fine..
    class Test
        public Test()
            System.out.println("In Test()");
        public Test(String arg)
            System.out.println("In Test(String)");
        public Test(String arg1, String arg2)
            System.out.println("In Test(String, String)");
        public static void main(String[] argv)
            Test test = new Test();
            Test test2 = new Test("hello");
            Test test3 = new Test("hello", "world");
    }And outputs the lines
    In Test()
    In Test(String)
    In Test(String, String)

  • Overloaded constructors & getters and setters problem

    I'm writing a driver class that generates two cylinders and displays some data. Problem is I don't understand the concept on overloaded constructors very well and seem to be stuck. What I'm trying to do is use an overloaded constructor for cylinder2 and getters and setters for cylinder1. Right now both are using getters and setters. Help would be appreciated.
    Instantiable class
    public class Silo2
        private double radius = 0;
        private double height = 0;
        private final double PI = 3.14159265;
        public Silo2 ()
            radius = 0;
            height = 0;       
       // Overloaded Constructor?
       public Silo2(double radius, double height) {     
          this.radius = radius;
          this.height = height;
       // Getters and Setters
       public double getRadius() {
          return radius;
       public void setRadius(double radius) {
          this.radius = radius;
       public double getHeight() {
          return height;
       public void setHeight(double height) {
          this.height = height;
       public double calcVolume()
           return PI * radius * radius * height;
       public double getSurfaceArea()
           return 2 * PI * radius * radius + 2 * PI * radius * height;
    Driver class I'm not going to show all the code as it's rather long. Here's snippets of what I have so far
    So here's input one using setters
    validateDouble reads from a public double method that validates the inputs, which is working fine.
    public static void main (String [ ]  args)
                Silo2 cylinder1 = new Silo2(); 
                Silo2 cylinder2 = new Silo2();
                //Silo inputs           
                double radSilo1 = validateDouble("Enter radius of Silo 1:", "Silo1 Radius");
                cylinder1.setRadius(radSilo1);
                double heiSilo1 = validateDouble("Enter height of Silo 1:", "Silo1 Height");
                cylinder1.setHeight(heiSilo1);
    Output using getters
    //Silo1 output
                JOptionPane.showMessageDialog(null,"Silo Dimensions 1 "   +
                    '\n' + "Radius = " + formatter.format(cylinder1.getRadius()) +
                    '\n' + "Height = " + formatter.format(cylinder1.getHeight()) +
                    '\n' + "Volume = " + formatter.format(cylinder1.calcVolume()) +
                    '\n' + "Surface Area = " + formatter.format(cylinder1.getSurfaceArea()));How can I apply an overloaded constructor to cylinder2?
    Edited by: DeafBox on May 2, 2009 12:29 AM

    DeafBox wrote:
    Hey man,
    My problem is that I don't now how to use an overloaded constructor. I'm new to this concept and want to use an overloaded contructor to display data for cylinder2, and getters and setters to display data for cylinder1.So, again, what in particular is your problem?
    Do you not know how to write a c'tor?
    Do you not know how to use a c'tor to intialize an object?
    Do you not understand overloading?
    Do you not realize that overloading c'tors is for all intents and purposes identical to overloading methods?

Maybe you are looking for