Overloading constructor question

The following douse not seem to work:-
class A {
     A( int i ) {
          System.out.println( "A constructor" + i );
class B {
     B( int i ) {
          System.out.println( "B constructor" + i );
class C extends A {
     C () { // line 17
          System.out.println( "C constructor" );
     public static void main( String[] args ) {
          C c = new C();
It complaines at line 17
A(int) in A cannot be applied to ()
C () {
^
This has totaly bafeld be. I thought it was OK to add overloaded constructors in inheratid classes but it seems to be complaining that I am replacing C(int) wit C(), i.e. the constructor in the subclass has diferent arguments. surly this should simply add an overloaded constructer?
Ben

The first statement in every constructor must be a call to either a) another constructor in that class or b) a constructor of the super class. If you do not specify a call to either, then the compiler automatically will insert a call to the no argument constructor of the super class. Since there isn't a no-arg constructor in A, the compiler complains that you are calling the A(int) constructor with no arguments. You need to either add a no argument constructor to A, or you need to call the A(int) constructor from the C constructor with some default value.
In case you didn't know, to call a super constructor from a subclass, you use the super keyword.
Example:
class A {
    A(int i) {}
class B extends A {
    B() {
        super(2);  //This call the A(int) constructor.
}

Similar Messages

  • 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.

  • 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?

  • Overloading constructor of a child that inherits from a class that inherits from Windows.Forms

    The title might be a bit confusing so here is the layout.
    - classHForm inherits System.Windows.Forms.Form
    - frmDoStuff inherits classHForm  (written by someone else and used in several applications)
      - does not have a constructor specifically defined, so I added the following thinking it would override the parent
    Sub Public New()
    End Sub
    Sub Public New(byval data as string)
    'do stuff
    End Sub
    In my code, I want to instantiate frmDoStuff, but I need to overload it's constructor and populate fields within this form. The problem I'm running into is that when I run this, it is using the constructor from classHForm and ignores any constructor in frmDoStuff.
    I guess you can't override the parent constructor? Is that why it won't work?
    I didn't want to overload the classHForm constructor, but I will if that's the way to go.
    my code:
    dim frm as new frmDoStuff(myString)
    Note: I would love to show actual code, but not allowed. Against company rules.

    Your code is similar. The value I pass into frmDoStuff is supposed to set a value for a textfield.
    Public Class frmDoStuff
    Inherits classHForm
    Public Sub New(ByVal s As String, ByVal gridData() as String)
    txtMyTextField.text = s LoadGrid(gridData)
    End Sub
    I also have a datagridview I need to populate in frmDoStuff and thought I would have another string or string array as a second parameter to the constructor and then call a routine from the constructor to populate the datagrid.
    of course, when I run it this way, the code is not being reached. I'll build an example as COR suggested and maybe someone will see where I'm going wrong.
    [UPDATE]
    I created a simple example and it worked. So, now I need to try to understand what is different in the actual code.
    Here is my example:
    Parent Class inherits form
    Imports System.Windows.Forms
    Public Class classMyForm
    Inherits System.Windows.Forms.Form
    Sub New()
    ' This call is required by the designer.
    InitializeComponent()
    ' Add any initialization after the InitializeComponent() call.
    End Sub
    End Class
    Public Class frmDoStuff
    Inherits classMyForm
    Public Sub New()
    ' This call is required by the designer.
    InitializeComponent()
    ' Add any initialization after the InitializeComponent() call.
    End Sub
    Public Sub New(ByVal sStuff As String)
    MyBase.New()
    InitializeComponent()
    'Populate the textbox
    TextBox1.Text = sStuff
    End Sub
    End Class
    Public Class frmMyForm
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim frm As New frmDoStuff(TextBox1.Text)
    frm.Show()
    End Sub
    End Class
    Just to recap. The actual parent was created a few years ago and the child form that I'm calling, "frmDoStuff" was created a couple years back and is used in several applications. I need to use it in my application, but I need to populate a couple
    controls when the form is loaded. As you can see in this example, I successfully overloaded the constructor to populate the textbox in frmDoStuff.
    In my real life situation, my overloaded constructor seems to be getting ignored when i step through the code. I'll go back and do some more testing.

  • Try blocks in overloaded constructors.

    I'm currently working on a program for my Data Structures class that will randomly generate lottery tickets for the user. I've designed a class to represent the tickets so that I can manipulate the data and such. I have one main constructor with 6 parameters and a few other overloaded constructors to provide default values when less than 6 arguments are provided in the call.
    Here's my problem: I think it would be cool to design a constructor that takes an int array as it's parameter with all the data contained in the array already. This seems like a great place to experiment with the try blocks so I can test that the array has enough values before the values are accessed. My current implementation of the try block conflicts with the semantics of using the "this" keyword in overloaded constructors: "this" must come first in the constructor. I'm not sure what to do, and since it's the first time I've ever even attempted to use try blocks, I don't have a clue what to ask...
    I have this ----------------------------------------->
    {noformat}{noformat}{noformat}public Ticket( int cap1, int low1, int high1, int cap2, int low2, int high2) {{noformat}{noformat} // Some initializations and method calls here{noformat}{noformat}}{noformat}{noformat}public Ticket( int ticketParams[] ) {{noformat}{noformat} try {{noformat}{noformat} this (ticketParams[0], ticketParams[1], ticketParams[2],{noformat}{noformat} ticketParams[3], ticketParams[4], ticketParams[5] );{noformat}{noformat} } catch(ArrayIndexOutOfBoundsException err) {{noformat}{noformat} System.out.println("Array argument does not contain enough data.");{noformat}{noformat} }{noformat}{noformat}}{noformat}
    ------------------------------------------------------------^
    Should I be trying to do this another way, or is this not possible -- or even sensible?

    Assert them on the caller side, not on the callee i.e. the consturctor.
    Anyway a try/catch for an ArrayIndexOutOfBoundsException is useless because the exception would throw a message similar to yours and it is fatal for the program run continuation.

  • Confused bout concept of Overloading Constructor

    Hi all...
    hope someone can clear this doubt of mine...
    I'd thought that Java supports overloading constructors but why is it that when I created two constructors for a class, the editor is telling me things like unresolved symbols for the second constructor?
    Although both constructors takes in 4 parameters, they are actually of different type and I can't understand why it won't work..
    can someone please clarify this with me?
    Thanks in advance! :D

    Thanks
    //this is the constructor classes
    public class ConnectionList extends JPanel{
        public ConnectionList(ObjectPanel initOPanel, int lt, JFrame parentPanel)
            oPanel = initOPanel;
            listType = lt;
            parent = parentPanel;
            objectName = oPanel.getCurrentObjectName();
            objectType = oPanel.getCurrentObjectType();
        public ConnectionList(String OName, int OType, int lt, JFrame parentPanel)
         listType = lt;
         parent = parentPanel;
         objectName = OName;
         objectType = OType;
    //I call to the class constructors using these:
    //no problem for this one (first constructor):
    inputList = new ConnectionList(oPanel, inputType, parentPanel);
    //oPanel is the ObjectPanel object
    //parent Panel is JFrame
    //inputType is an integer
    //somehow this one gives the error of unresolved symbols (2nd constructor)
    checkList = new ConnectionList(objectN, objectT, 1, parentPanel);
    //objectN, objectT are all string objects
    //parentPanel is the JFrame object
    //and this...Thanks again!

  • Urgent constructor question..

    I'm trying to call this Flower class in another class called Garden, in which I created a new Flower by using a statement
    private Flower lastflower;
    and it's saying it cannot find the symbol - constructor Flower.
    Can anyone tell me why and help correct this problem?
    Below is the code for my Flower class.
    Any help is really appreciated, it's for my Java class!
    import objectdraw.*;
    import java.awt.*;
    * Write a description of class Flower here.
    * @author (your name)
    * @version (a version number or a date)
    public class Flower
        protected FilledOval dot;
        protected FilledRect stem;
        protected FilledOval petal1;
        protected FilledOval petal2;
        protected static final int boundary = 100;
        protected RandomIntGenerator colorGen =
                new RandomIntGenerator(0,255);
        protected Color petalColor;
        protected Boolean flowerContains=false;
        private DrawingCanvas canvas;
        public void changeColor(){
        dot = new FilledOval(150,150,15,15, canvas);
        dot.setColor(Color.YELLOW);
        petalColor = new Color(colorGen.nextValue(),
                                    colorGen.nextValue(),
                                    colorGen.nextValue());
        petal1.setColor(petalColor);
        petal2.setColor(petalColor);
        public void grow(Location point){
        stem = new FilledRect (dot.getX()+3, dot.getY()+10, 10, 10, canvas);
        stem.setColor(Color.GREEN);
        if (dot.getY()>boundary){
            dot.move(0,-4);
        else{
         petal1 = new FilledOval(dot.getX()-12, dot.getY()-25, 40,70,canvas);
         petal2 = new FilledOval(dot.getX()-25, dot.getY()-10, 70,40,canvas);
         dot.sendToFront();
         stem.sendToBack();
         petal1.setColor(petalColor);
         petal2.setColor(petalColor);
        public Boolean flowerContains(Location point){
            if (petal1.contains(point)){
                return true;
            else if (petal2.contains(point)){
                return true;
            else if (dot.contains(point)){
                return true;
            else{
                return false;
    }

    I don't care how fucking urgent you think it is, it isn't to us. We will answer your question when and how we feel llike it. Have some manners and if you must, then bump your original post. Don't create another time wasting piece of cr&#97;p!

  • Inheritance constructor question

    Hi
    I am having trouble understanding how the superclasses constructor works in inheritance:
    Please look at the following code:
    public class mySuperClass
         mySuperClass ()
              System.out.println("super1");
    public class myClass extends mySuperClass
         myClass ()
              System.out.println("hello1");
         myClass (int q)
              System.out.println("hello2");
    public static void main(String[] args)
              myClass o = new myClass ();
              myClass o = new myClass (3);
    When I run this program the console results are:
    super1
    hello1
    super1
    hello2
    Why does the constructor of the super class run even when I overload it?
    Thanks
    Aharon

    I think you meant to write "Why does the constructor of the super class run even when I overrideit?"
    And the point is you can't override a constructor (technically, they are not even methods). A constructor in a derived class (MyClass) must call a constructor in its superclass (MySuperClass ). If you do not explicitly call one:
    MyClass (int q) {
        super(...arguments...); // <---
        System.out.println("hello2");
    }There will be an attempt to implicitly to invoke super();

  • Constructor question?

    I am working on a class called Firm and it has an array of employee objects as its data field. Its constructor has an array of employee objects as its parameter: it initializes the data field array by copying references from the parameter array in a loop. Its main method creates one or two HourlyEmployee objects and one or more exemptEmployee objects. Then it calls setPay for one HourlyEmployee object and one ExemptEmployee objects and prints the results. Then it calls methods setPay and toString for these two objects (calling println, annotate this part of processing so that the output is readable).
    What I have so far is, Employee being an abstract class that has a Constructor, and methods setPay(), getPay(), and toString. Subclasses HourlyEmployee and ExemptEmployee each with their own constructors and methods getPay() and setPay() along with toString() methods.
    Currently this is what I have for code for my Firm class:
    public class Firm
    private Employee[] empObj;
    Firm(Emp[] empObj)
    for(int i = 0;i<empObj.length;++i)
    arrObj=empObj;
    }Does my constructor have an array of employee objects as its parameters? Do I need to create an Object array[] arrObj?

    if Firm's constructor is being passed an Employee array, then just save that reference.
    public class Firm
      private Employee[] empObj;
      public Firm(Emp[] empObj)
        this.empObj = empObj;
    }Alternatively, you may wish to copy the parameter so that changes to the original (made outside by the guy who passed it to you, for example) don't affect it. In that case, change Firm's constructor to do this:
    this.empObj = new Employee[empObj.length];
    for (int i = 0; i < empObj.length; ++i)
      this.empObj[i] = empObj;
    // or, you may even want to "deep-copy" it like this, if you created
    // a "copy-constructor" or "clone" method:
    this.empObj[i] = new Employee(empObj[i]);
    //or
    this.empObj[i] = (Employee) empObj[i].clone();

  • Overloaded methods question

    I guess I don't understand overloaded methods as well as I thought I did, because I'm confused about some behavior I'm seeing in my Java program. Here's a sample program that I wrote up to demonstrate the issue:
    public class Polymorphism
         static class Shape
              public void test()
                   System.out.println( "In Shape" );
         static class Rectangle extends Shape
              int height, width;
              public Rectangle( int height, int width )
                   this.height = height;
                   this.width = width;
              public void test()
                   System.out.println( "In Rectangle" );
              public boolean equals( Rectangle rect )
                   return ( height == rect.height ) && ( width == rect.width );
         public static void main( String[] args )
              Shape shape = new Rectangle( 5, 7 );
              shape.test();
              Shape shape1 = new Rectangle( 3, 4 );
              Shape shape2 = new Rectangle( 3, 4 );
              System.out.println( shape1.equals( shape2 ) );
              System.out.println( ((Rectangle)shape1).equals( shape2 ) );
              System.out.println( shape1.equals( (Rectangle)shape2 ) );
              System.out.println( ((Rectangle)shape1).equals( (Rectangle)shape2 ) );
    }And the output looks like this:
    In Rectangle
    false
    false
    false
    trueThe first call to "test()" calls the Rectangle's test method, as I would have expected. This happens despite the fact that shape is declared as a Shape.
    Here's where I get confused. I would have thought the next four calls to println would have output "true" every time, because shape1 and shape2 are Rectangles, hence, I would have expected that Rectangle's "equals()" method would have been called each time. But apparently it's only being called in the last case, when I cast both shape1 and shape2 to be Rectangles. (Presumably, Object.equals() is being called, and it's appropriately returning "false" because the objects are not the same instance.)
    So this behavior seems inconsistent to me. Why did the first call to "test()" invoke Rectangle.test() even though I declared it as a Shape, yet the succeeding calls to shape1 invoke Shape.equals() rather than Rectangle.equals(), despite the fact that the objects are truly Rectangles?
    Can anyone explain this to me, or point me to a tutorial that would describe this behavior?
    Thanks.

    Case 1 and Case 2 seem analogous to me, yet their
    behaviors are different. (There is one difference
    between the two cases, and that is that in case 1 I'm
    overriding the test() method, while in case 2 I'm
    overloading equals(). Overriding vs. overloading.
    Though clearly these are different concepts, I guess
    it never would have occurred to me that whether a
    method was overridden vs. overloaded made such a
    difference in how invocation worked.)You're right: it's the diffference between overriding and overloading.
    I'll try to formulate it differently:
    At compile-time, the compiler, based on the declared type of the Object the method's called on, and based on the declared types of the arguments, determines which method'll get called (a method is defined by its name and its signature. I don't think the return type matters in this context).
    In the test() case, the compiler looks for a method in class Shape and finds: test().
    In your "third case", the compiler looks for a method named "equals" in class Shape with the argument type: "Rectangle", finds none, so it takes: equals(Object)
    At runtime, the method is looked for in the Object it's invoked on, that is a Rectangle.
    In the test() case, it looks for the method: test(). Since that is declared in the Rectangle class, it takes the overridden method.
    But in the "third case", there's no equals(Object) method, so it takes the super.
    So I apologize if no one can think of a way to make
    this clearer to me, but I still have some subtle
    confusion on the issue.It is a confusing topic. That's why I pointed out itchyscratchy's reply, who made a good point telling to avoid having to rely on overloaded methods generally. Overriding is complicated enough.

  • Constructor question - dealing with protected methods

    Hi all, I'm trying to run a protected method, got somewhere by making the class a subclass - but not too sure about where to put the constructor for a class I'm trying to use (IQRegister). Can anyone help and point me in the right direction as to what I did wrong?
    public class Registration extends IQRegister {
    //Create new instance of ConnectionBean
    ConnectionBean conBean = new ConnectionBean();
    InfoQueryBuilder iqb = new InfoQueryBuilder();
    InfoQuery iq;
    //IQRegisterBuilder iqRegb = new IQRegisterBuilder();
    public Registration( IQRegisterBuilder iqRegb ) {
    super( iqRegb );
    //This constructor needs to go somewhere that will work>>>>>>>>>>>>>>
    IQRegister iqReg = new IQRegister( iqRegb );
    public void regUser() {
    String server = JOptionPane.showInputDialog( "Enter Server address" );
    InetAddress inetaddress;
    try {
    conBean.connect( inetaddress = InetAddress.getByName( server ));
    catch( UnknownHostException unknownhostexception ) {
    Object aobj[] = {
    "Cancel", "OK"
    int i = JOptionPane.showOptionDialog(null, "Retry Server?", server +
    ": Not Responding", -1, 2, null, aobj, aobj[1]);
    if( i == 1 )
    regUser();
    System.out.println( "Cannot resolve " + server + ":" + unknownhostexception.toString ());
    return;
    catch( IOException ioexception ) {
    Object aobj1[] = {
    "Cancel", "OK"
    int j = JOptionPane.showOptionDialog( null, "Cannot Connect to:",
    server,-1, 2, null, aobj1, aobj1[1] );
    if( j == 1 )
    regUser();
    System.out.println( "Cannot connect " + server);
    return;
    System.out.println( "Registering User" );
    registrationProcess();
    public void registrationProcess () {
    try {
    //Need to getXMLNS packet method getXMLNS() is protected
    iqReg.getXMLNS();
    catch ( InstantiationException e ) {
    System.out.println( "Error in building Registration packet" );
    String username = JOptionPane.showInputDialog( "Enter: Username" );
    String password = JOptionPane.showInputDialog( "Enter: Password" );
    ERROR:
    Registration.java:108: cannot resolve symbol
    symbol : variable iqReg
    location: class Registration
    iqReg.getXMLNS();
    ^
    1 error
    Thanks again :)

    Made some changes to code but getting some varied error here:
    Registration.java:31: <identifier> expected
    iqReg = new IQRegister( iqRegb );
    ^
    Registration.java:31: cannot resolve symbol
    symbol : class iqReg
    location: class Registration
    iqReg = new IQRegister( iqRegb );
    ^
    Registration.java:104: cannot resolve symbol
    symbol : variable iqReg
    location: class Registration
    iqReg.getXMLNS();
    ^
    3 errors
    CODE:
    public class Registration extends IQRegister {
    //Create new instance of ConnectionBean
    ConnectionBean conBean = new ConnectionBean();
    InfoQueryBuilder iqb = new InfoQueryBuilder();
    InfoQuery iq;
    //IQRegisterBuilder iqRegb = new IQRegisterBuilder();
    //This constructor problem here>>>>>>>>>>>>
    iqReg = new IQRegister( iqRegb );
    public Registration( IQRegisterBuilder iqRegb ) {
    super( iqRegb );
    .......same code..... as above....
    Thank you so much for the guidance..

  • Constructor question.Help!

    Hi,
    I need help!I've been trying to do this for several hours now.
    My program takes in parameters a file cellSig.txt and a int in the main program and the int gives the number of for loops that need to be run.Now in the for loop,I have a constructor for class ranData.
    for(int model = 0;model<= cross; model++){
    ranData objData = new ranData(filename);
    }//cross is the parameter int given by user
    ranData basically takes the main file cellSig.txt and randomises and divides into 2 other files.It is vital that there should be different files for every 'for' loop.
    However I compile and
    ./ranData.java:5: illegal start of type
    try{
    ^
    ./ranData.java:40: <identifier> expected
    ^
    keyInput.java:18: cannot resolve symbol
    symbol : constructor ranData (java.lang.String)
    location: class ranData
    ranData objData = new ranData(filename);
    I'm posting the ranData.java code below.Pls help..I'm not sure what is wrong.
    import java.io.*;
    import java.util.*;
    public class ranData{
         ArrayList list = new ArrayList();
         try{
         BufferedReader in = new BufferedReader(new FileReader(filename));
         String FileToRead = in.readLine();
         while(FileToRead!= null){
              list.add(FileToRead);
              FileToRead = in.readLine();
         in.close();
         in = null;
         Collections.shuffle(list);
         List trainList = list.subList(0,2000);
         List testList = list.subList(2000,list.size());
         BufferedWriter  objBW =  new BufferedWriter(new FileWriter("cellSig.names"));
         BufferedWriter  objBWt =  new BufferedWriter(new FileWriter("cellSig.names"));
         Iterator x = trainList.iterator();
         Iterator y = testList.iterator();
         String tmp = "";
         String temp = "";
         while(x.hasNext()){
              tmp =(String) x.next() ;
              objBW.write(tmp);
              objBW.newLine();
         while(y.hasNext()){
              temp = (String)y.next() ;
              objBWt.write(temp);
              objBWt.newLine();
         objBW.close();
         objBWt.close();
         objBW = objBWt = null;
         x = y = null;
         }catch(IOException e){
         System.out.println(e);
    [\code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    public RanData(String filename){     
         Filename = filename;
         try{
         BufferedReader in = new BufferedReader(new FileReader(Filename));
         String FileToRead = in.readLine();You are closing the constructor and start coding again without declaring the try catch within a method. Try this:
    import java.io.*;
    import java.util.*;
    public class RanData{
         ArrayList list = new ArrayList();
         public String Filename;
         public RanData(String filename){     
         Filename = filename;
         try{
         BufferedReader in = new BufferedReader(new FileReader(Filename));
         String FileToRead = in.readLine();
         while(FileToRead!= null){
              list.add(FileToRead);
              FileToRead = in.readLine();
         in.close();
         in = null;
         Collections.shuffle(list);
         List trainList = list.subList(0,2000);
         List testList = list.subList(2000,list.size());
         BufferedWriter  objBW =  new BufferedWriter(new FileWriter("cellSig.names"));
         BufferedWriter  objBWt =  new BufferedWriter(new FileWriter("cellSig.names"));
         Iterator x = trainList.iterator();
         Iterator y = testList.iterator();
         String tmp = "";
         String temp = "";
         while(x.hasNext()){
              tmp =(String) x.next() ;
              objBW.write(tmp);
              objBW.newLine();
         while(y.hasNext()){
              temp = (String)y.next() ;
              objBWt.write(temp);
              objBWt.newLine();
         objBW.close();
         objBWt.close();
         objBW = objBWt = null;
         x = y = null;
         }catch(IOException e){
         System.out.println(e);
    }I also reccomend you to read a good Java beginners books

  • Overloaded constructors, final and assert

    I am having some difficulties of using final variables and still have the ability to check parameters in the constructor.
    For example take this class:
    class MyObject {
    final String id;
    final String value;
    public MyObject(String id, String value) {
    assert id != null : "error";
    assert value != null : "error";
    this.id = value;
    this.value = value;
    public MyObject(Wrapper wrapper) {
    assert wrapper != null : "error";
    this(wrapper.getId(), wrapper.getValue());
    The above code won't compile because the assert is not allowed before the call to the other constructor.
    I cannot do the initializing of variables in a normal method, because I cannot assign to the variables at that point.
    I can use a static method that created to object, but is that really a good idea?
    Any suggestions?

    Generally, assert in parameters of public methods is not recommended.
    Assertion is for situations that are even more exceptional than Exceptions,
    for example, to detect bugs in the code.
    Theoretically, in public methods you don�t have to use assert to verify if the
    parameter is null or not null. You have to use if statement and throw
    NullPointerException,for example. If the method were private, like your
    init( ) method, so that�s ok and you could use assertion.It does not make sense to me why I would use asserts in private methods
    and not for public ones. Especially since the same parameters might
    end up in a private method anyway.
    For me asserts are about pre-conditions, post-conditions and constraints.
    I especially find them useful for pre-conditions and making very clear
    to the caller what I expect of him.
    A good article about assert can be found at javaworld
    http://www.javaworld.com/javaworld/jw-12-2001/jw-1214-assert.html
    Anyway, it's kinda off-topic, because if I would use an if statement
    and throw an exception, I have the exact same problem!
    This does not compile:
    public MyObject(Wrapper wrapper) {
        if (wrapper != null)
            throw NullPointerException("error");
        this(wrapper.getId(), wrapper.getValue());
    }

  • AIA FP 11g - Service Constructor Question

    Hi All,
    I am trying to create the Provider ABCS impl using the Service Constructor. I have defined the Solution Service Component in the AIA Project Lifecycle Workbench as BAERP Create Purchase Order List Ebiz Provider ABCS. The CreatePurchaseOrderList method of the PurchaseOrderEBS will invoke this ABCS with a list of Purchase Orders.
    To create the Service Contructor, these are the steps that I follow,
    1. Create New Project -> Business Tier -> AIA -> AIA Service Component Project
    2. Service Description: Select the Solution Service Component from the AIA Project Lifecycle Workbench
    3. Service Details: Product Code: Ebiz, Application Name: Ebiz, Application Id: EBIZ_01, Application Short Name: Ebiz, Service Operation: Create, Service Type: Provider ABCS ( Only relevant attributes are given)
    4. Service Object: WSDL: Select PurchaseOrderEBSV1.wsdl from EnterpriseBusinessServiceLibrary, Operations: CreatePurchaseOrderList
    5. Target Service Details: I am selecting the wsdl of a deployed composite, which inserts a list of Purchase Orders into a database, Operations: Process
    6. I click Finish - The ABCS as well as the BPEL process that gets created is CreatePurchaseOrderEbizProvABCSImpl, where as I was expecting it to be created as CreatePurchaseOrderListEbizProvABCSImpl.
    Did I miss something here, or should I be referring to the ABCS as CreatePurchaseOrderEbizProvABCSImpl?
    Regards,
    Anish.

    Hi,
    Check the Object Name field in Step 4 of Service Constructor. Ensure it is PurchaseOrderList, If it was jus PurchaseOrder you edit and append List to it.
    After Finish, your Prov ABCS will be named as CreatePurchaseOrderListEbizProvABCSImpl.
    Regards,
    Rahul

Maybe you are looking for