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.
Similar Messages
-
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 AMDeafBox 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 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?
BenThe 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.
} -
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! :DThanks
//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! -
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());
} -
Cannot find symbol while referring to an overloaded constructor
Hi, I've a VERY strange problem. It's an hour I'm trying to work this out without any luck....
here is my code
public DueDPanel(int limite, int valore, int incremento) throws NumberOutOfBoundException
this.limite=limite;
setValore(valore);
upBy=incremento;
public DueDPanel(int limite, int valore) throws NumberOutOfBoundException
{ DueDPanel(limite,valore,1); }
public DueDPanel(int limite) throws NumberOutOfBoundException
{ DueDPanel(limite,0,1); }
public DueDPanel() throws NumberOutOfBoundException
{ DueDPanel(99,0,1); }I get a c-time error
.\DueDPanel.java:25: cannot find symbol
symbol : method DueDPanel(int,int,int)
location: class DueDPanel
{ DueDPanel(limite,valore
^
.\DueDPanel.java:28: cannot find symbol
symbol : method DueDPanel(int,int,int)
location: class DueDPanel
{ DueDPanel(limite,0,1);
^
.\DueDPanel.java:31: cannot find symbol
symbol : method DueDPanel(int,int,int)
location: class DueDPanel
{ DueDPanel(99,0,1); }
How could it be? why in the world it cannot find my int,int,int method?
I'm damn sure this is an easy problem, but..... thankyou sooooo much!!Ok, a superior-class developer friend of mine found a solution.
I simply replaced the method indetifier with this(....).
public DueDPanel() throws NumberOutOfBoundException
{ this(99,0,1); }Could someone please explain why this didn't work as I expeced? -
How does one then go about overloading a contructor of the main class have the object called in the main method, say:
public class ShadeArea //extends whatever
public ShadeArea()
// Structure the layout of the app. here
public ShadeArea(Locale locale) // overloaded contructor
locale = Locale.getDefault();
public static void main(String args[])
// Render the app
ShadeArea shade = new ShadeArea();
/* The problem lies herein
** How do I go about, as an example, setting the locale
}How do I get an object from an overloaded constructor to work with, say, the other objects of the first constructor?
Hope u understand my question...
Thx!
Reformer!THe problem is that locale is local (I hate these words), meaning that once the constructor is done, locale is gone.
You need to use class variable.
Here is what it might look like:
public class ShadeArea() {
Locale _locale;
public ShadeArea() {}
public ShadeArea(Locale locale) {
_locale = locale;
_locale = Locale.getDefault();
public static void main(String args[]) { // Render the app
ShadeArea shade = new ShadeArea();
//now _locale is available for use
}Your code, however doesn't seem to have much sense, since the locale variable in the constructor never really gets used.
I think you should get some more information about local/global variables and parameters to methods.
HTH
M -
Passing arraylist between constructors?
Hi guys,
I've pretty new to java, and I think i'm having a little trouble
understanding scope. The program I'm working on is building a jtree
from an xml file, to do this an arraylist (xmlText) is being built and
declared in the function Main. It's then called to an overloaded
constructor which processes the XML into a jtree:
public Editor( String title, ArrayList xmlText ) throws
ParserConfigurationException
Later, in the second constructor which builds my GUI, I try and call
the same arraylist so I can parse this XML into a set of combo boxes,
but get an error thrown up at me that i'm having a hard time solving- :
public Editor( String title ) throws ParserConfigurationException
// additional code
// Create a read-only combobox- where I get an error.
String [] items = (String []) xmlText.toArray (new String[
xmlText.size () ]);
JComboBox queryBox = new JComboBox(items);
JComboBox queryBox2 = new JComboBox(items);
JComboBox queryBox3 = new JComboBox(items);
JComboBox queryBox4 = new JComboBox(items);
JComboBox queryBox5 = new JComboBox(items);
This is the way I understand the Arraylist can be converted to a string
to use in the combo boxs. However I get an error thrown up at me here
at about line 206, which as far as I understand, is because when the
overloaded constructor calls the other constructor:
public Editor( String title ) throws ParserConfigurationException -
It does not pass in the variable xmlText.
I'm told that the compiler complains because xmlText is not defined
at that point:
- it is not a global variable or class member
- it has not been passed into the function
and
- it has not been declared inside the current function
Can anyone think of a solution to this problem? As I say a lot of this
stuff is still fairly beyond me, I understand the principles behind the
language and the problem, but the solution has been evading me so far.
If anyone could give me any help or a solution here I'd be very
grateful- I'm getting totally stressed over this.
The code I'm working on is below, I've highlighted where the error
crops up too- it's about line 200-206 area. Sorry for the length, I was
unsure as to how much of the code I should post.
public class Editor extends JFrame implements ActionListener
// This is the XMLTree object which displays the XML in a JTree
private XMLTree XMLTree;
private JTextArea textArea, textArea2, textArea3;
// One JScrollPane is the container for the JTree, the other is for
the textArea
private JScrollPane jScroll, jScrollRt, jScrollUp,
jScrollBelow;
private JSplitPane splitPane, splitPane2;
private JPanel panel;
// This JButton handles the tree Refresh feature
private JButton refreshButton;
// This Listener allows the frame's close button to work properly
private WindowListener winClosing;
private JSplitPane splitpane3;
// Menu Objects
private JMenuBar menuBar;
private JMenu fileMenu;
private JMenuItem newItem, openItem, saveItem,
exitItem;
// This JDialog object will be used to allow the user to cancel an exit
command
private JDialog verifyDialog;
// These JLabel objects will be used to display the error messages
private JLabel question;
// These JButtons are used with the verifyDialog object
private JButton okButton, cancelButton;
private JComboBox testBox;
// These two constants set the width and height of the frame
private static final int FRAME_WIDTH = 600;
private static final int FRAME_HEIGHT = 450;
* This constructor passes the graphical construction off to the
overloaded constructor
* and then handles the processing of the XML text
public Editor( String title, ArrayList xmlText ) throws
ParserConfigurationException
this( title );
textArea.setText( ( String )xmlText.get( 0 ) + "\n" );
for ( int i = 1; i < xmlText.size(); i++ )
textArea.append( ( String )xmlText.get( i ) + "\n" );
try
XMLTree.refresh( textArea.getText() );
catch( Exception ex )
String message = ex.getMessage();
System.out.println( message );
}//end try/catch
} //end Editor( String title, String xml )
* This constructor builds a frame containing a JSplitPane, which in
turn contains two
JScrollPanes.
* One of the panes contains an XMLTree object and the other contains
a JTextArea object.
public Editor( String title ) throws ParserConfigurationException
// This builds the JFrame portion of the object
super( title );
Toolkit toolkit;
Dimension dim, minimumSize;
int screenHeight, screenWidth;
// Initialize basic layout properties
setBackground( Color.lightGray );
getContentPane().setLayout( new BorderLayout() );
// Set the frame's display to be WIDTH x HEIGHT in the middle of
the screen
toolkit = Toolkit.getDefaultToolkit();
dim = toolkit.getScreenSize();
screenHeight = dim.height;
screenWidth = dim.width;
setBounds( (screenWidth-FRAME_WIDTH)/2,
(screenHeight-FRAME_HEIGHT)/2, FRAME_WIDTH,
FRAME_HEIGHT );
// Build the Menu
// Build the verify dialog
// Set the Default Close Operation
// Create the refresh button object
// Add the button to the frame
// Create two JScrollPane objects
jScroll = new JScrollPane();
jScrollRt = new JScrollPane();
// First, create the JTextArea:
// Create the JTextArea and add it to the right hand JScroll
textArea = new JTextArea( 200,150 );
jScrollRt.getViewport().add( textArea );
// Next, create the XMLTree
XMLTree = new XMLTree();
XMLTree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION
XMLTree.setShowsRootHandles( true );
// A more advanced version of this tool would allow the JTree to
be editable
XMLTree.setEditable( false );
// Wrap the JTree in a JScroll so that we can scroll it in the
JSplitPane.
jScroll.getViewport().add( XMLTree );
// Create the JSplitPane and add the two JScroll objects
splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, jScroll,
jScrollRt );
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(200);
jScrollUp = new JScrollPane();
jScrollBelow=new JScrollPane();
// Here is were the error is coming up
String [] items = (String []) xmlText.toArray (new String[
xmlText.size () ]);
JComboBox queryBox = new JComboBox(items);
JComboBox queryBox2 = new JComboBox(items);
JComboBox queryBox3 = new JComboBox(items);
JComboBox queryBox4 = new JComboBox(items);
JComboBox queryBox5 = new JComboBox(items);
* I'm adding the scroll pane to the split pane,
* a panel to the top of the split pane, and some uneditible
combo boxes
* to them. Then I'll rearrange them to rearrange them, but
unfortunately am getting an error thrown up above.
panel = new JPanel();
panel.add(queryBox);
panel.add(queryBox2);
panel.add(queryBox3);
panel.add(queryBox4);
panel.add(queryBox5);
jScrollUp.getViewport().add( panel );
// Now building a text area
textArea3 = new JTextArea(200, 150);
jScrollBelow.getViewport().add( textArea3 );
splitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
jScrollUp, jScrollBelow);
splitPane2.setPreferredSize( new Dimension(300, 200) );
splitPane2.setDividerLocation(100);
splitPane2.setOneTouchExpandable(true);
// in here can change the contents of the split pane
getContentPane().add(splitPane2,BorderLayout.SOUTH);
// Provide minimum sizes for the two components in the split pane
minimumSize = new Dimension(200, 150);
jScroll.setMinimumSize( minimumSize );
jScrollRt.setMinimumSize( minimumSize );
// Provide a preferred size for the split pane
splitPane.setPreferredSize( new Dimension(400, 300) );
// Add the split pane to the frame
getContentPane().add( splitPane, BorderLayout.CENTER );
//Put the final touches to the JFrame object
validate();
setVisible(true);
// Add a WindowListener so that we can close the window
winClosing = new WindowAdapter()
public void windowClosing(WindowEvent e)
verifyDialog.show();
addWindowListener(winClosing);
} //end Editor()
* When a user event occurs, this method is called. If the action
performed was a click
* of the "Refresh" button, then the XMLTree object is updated using
the current XML text
* contained in the JTextArea
public void actionPerformed( ActionEvent ae )
if ( ae.getActionCommand().equals( "Refresh" ) )
try
XMLTree.refresh( textArea.getText() );
catch( Exception ex )
String message = ex.getMessage();
ex.printStackTrace();
}//end try/catch
else if ( ae.getActionCommand().equals( "OK" ) )
exit();
else if ( ae.getActionCommand().equals( "Cancel" ) )
verifyDialog.hide();
}//end if/else if
} //end actionPerformed()
// Program execution begins here. An XML file (*.xml) must be passed
into the method
public static void main( String[] args )
String fileName = "";
BufferedReader reader;
String line;
ArrayList xmlText = null;
Editor Editor;
// Build a Document object based on the specified XML file
try
if( args.length > 0 )
fileName = args[0];
if ( fileName.substring( fileName.indexOf( '.' ) ).equals(
".xml" ) )
reader = new BufferedReader( new FileReader( fileName )
xmlText = new ArrayList();
while ( ( line = reader.readLine() ) != null )
xmlText.add( line );
} //end while ( ( line = reader.readLine() ) != null )
// The file will have to be re-read when the Document
object is parsed
reader.close();
// Construct the GUI components and pass a reference to
the XML root node
Editor = new Editor( "Editor 1.0", xmlText );
else
help();
} //end if ( fileName.substring( fileName.indexOf( '.' )
).equals( ".xml" ) )
else
Editor = new Editor( "Editor 1.0" );
} //end if( args.length > 0 )
catch( FileNotFoundException fnfEx )
System.out.println( fileName + " was not found." );
exit();
catch( Exception ex )
ex.printStackTrace();
exit();
}// end try/catch
}// end main()
// A common source of operating instructions
private static void help()
System.out.println( "\nUsage: java Editor filename.xml" );
System.exit(0);
} //end help()
// A common point of exit
public static void exit()
System.out.println( "\nThank you for using Editor 1.0" );
System.exit(0);
} //end exit()
class newMenuHandler implements ActionListener
public void actionPerformed( ActionEvent ae )
textArea.setText( "" );
try
// Next, create a new XMLTree
XMLTree = new XMLTree();
XMLTree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION );
XMLTree.setShowsRootHandles( true );
// A more advanced version of this tool would allow the JTree
to be editable
XMLTree.setEditable( false );
catch( Exception ex )
String message = ex.getMessage();
ex.printStackTrace();
}//end try/catch
}//end actionPerformed()
}//end class newMenuHandler
class openMenuHandler implements ActionListener
JFileChooser jfc;
Container parent;
int choice;
openMenuHandler()
super();
jfc = new JFileChooser();
jfc.setSize( 400,300 );
jfc.setFileFilter( new XmlFileFilter() );
parent = openItem.getParent();
}//end openMenuHandler()
public void actionPerformed( ActionEvent ae )
// Displays the jfc and sets the dialog to 'open'
choice = jfc.showOpenDialog( parent );
if ( choice == JFileChooser.APPROVE_OPTION )
String fileName, line;
BufferedReader reader;
fileName = jfc.getSelectedFile().getAbsolutePath();
try
reader = new BufferedReader( new FileReader( fileName ) );
textArea.setText( reader.readLine() + "\n" );
while ( ( line = reader.readLine() ) != null )
textArea.append( line + "\n" );
} //end while ( ( line = reader.readLine() ) != null )
// The file will have to be re-read when the Document
object is parsed
reader.close();
XMLTree.refresh( textArea.getText() );
catch ( Exception ex )
String message = ex.getMessage();
ex.printStackTrace();
}//end try/catch
jfc.setCurrentDirectory( new File( fileName ) );
} //end if ( choice == JFileChooser.APPROVE_OPTION )
}//end actionPerformed()
}//end class openMenuHandler
class saveMenuHandler implements ActionListener
JFileChooser jfc;
Container parent;
int choice;
saveMenuHandler()
super();
jfc = new JFileChooser();
jfc.setSize( 400,300 );
jfc.setFileFilter( new XmlFileFilter() );
parent = saveItem.getParent();
}//end saveMenuHandler()
public void actionPerformed( ActionEvent ae )
// Displays the jfc and sets the dialog to 'save'
choice = jfc.showSaveDialog( parent );
if ( choice == JFileChooser.APPROVE_OPTION )
String fileName;
File fObj;
FileWriter writer;
fileName = jfc.getSelectedFile().getAbsolutePath();
try
writer = new FileWriter( fileName );
textArea.write( writer );
// The file will have to be re-read when the Document
object is parsed
writer.close();
catch ( IOException ioe )
ioe.printStackTrace();
}//end try/catch
jfc.setCurrentDirectory( new File( fileName ) );
} //end if ( choice == JFileChooser.APPROVE_OPTION )
}//end actionPerformed()
}//end class saveMenuHandler
class exitMenuHandler implements ActionListener
public void actionPerformed( ActionEvent ae )
verifyDialog.show();
}//end actionPerformed()
}//end class exitMenuHandler
class XmlFileFilter extends javax.swing.filechooser.FileFilter
public boolean accept( File fobj )
if ( fobj.isDirectory() )
return true;
else
return fobj.getName().endsWith( ".xml" );
}//end accept()
public String getDescription()
return "*.xml";
}//end getDescription()
}//end class XmlFileFilter
} //end class Editor
Sorry if this post has been a bit lengthy, any help you guys could give
me solving this would be really appreciated.
Thanks,
Iain.Hey. Couple pointers:
When posting, try to keep code inbetween code tags (button between spell check and quote original). It will pretty-print the code.
Posting code is good. Usually, though, you want to post theminimum amount of code which runs and shows your problem.
That way people don't have to wade through irrelevant stuff and
they have an easier time helping.
http://homepage1.nifty.com/algafield/sscce.html
As for your problem, this is a scope issue. You declare an
ArrayList xmlText in main(). That means that everywhere after
the declaration in main(), you can reference your xmlText.
So far so good. Then, inside main(), you call
Editor = new Editor( "Editor 1.0", xmlText );Now you've passed the xmlText variable to a new method,
Editor(String title, ArrayList xmlText) [which happens to be a
constructor, but that's not important]. When you do that, you
make the two variables title and xmlText available to the whole
Editor(String, ArrayList) method.
This is where you get messed up. You invoke another method
from inside Editor(String, ArrayList). When you call
this(title);you're invoking the method Editor(String title). You aren't passing
in your arraylist, though. You've got code in the Editor(String) method
which is trying to reference xmlText, but you'd need to pass in
your ArrayList in order to do so.
My suggestion would be to merge the two constructor methods into
one, Editor(String title, ArrayList xmlText). -
Hi, i got a question in my exam paper which went:
Write a program in Java(using BlueJ) to generate the following pattern for the first 'n' number of rows using overloaded functions
Following is the output for 5 rows:
a) 123454321 b) .... c) ...................
1234 4321
123 321
12 21
1 1
The patterns are not important, but I dont understand what overloaded functions mean. Also i have heard about overloaded constructors and I would like to know what they are too. Ive searched on the internet but i cant get answers that explain it properly. Would be glad to receive some clarification. Thanks
Message was edited by:
OverkillWell I cant really predict the questions that will come in my exam will I? Now after my exam is over , i tried to solve many of the problems i couldn't get , and i solved most, but I could not solve some.
All im asking for is help in solving those.. why are you hostile about that ? -
Problem with bool data type in overloading
Please find the following error.
I did following typedef:
typedef bool Boolean;
typedef signed int Sint32;
Problem description:
This error is occurring because Sun CC 5.9 or Solaris 9 g++ considers bool data type as signed Integer, when passed as an constructor argument. First, it is overloading the constructor with �bool� data type and when it comes the turn of �signed integer� to overload constructor, the compiler is giving an error �cannot be overloaded�. The error �redefinition� is also due to bool data type.
Could please let me know, whether i need to add ant compiler option on Sun CC
ERROR in g++:-
( /usr/local/bin/g++ -DSOLARIS_PLATFORM -DUNIX -DPEGASUS_PLATFORM_SOLARIS_SPARC_GNU -DPEGASUS_OS_SOLARIS -DPEGASUS_HAVE_TEMPLATE_SPECIALIZATION -DEXPAND_TEMPLATES -DPEGASUS_USE_EXPERIMENTAL_INTERFACES -Wno-non-template-friend -DTEST_VAI -D__EXTERN_C__ -Dregister= -D_POSIX_PTHREAD_SEMANTICS -Wno-deprecated -DAUTOPASS_DISABLED -DCLUSTER_GEN_APP -DSTAND_ALONE_INTEG -I"/TESTBUILD/p2.08.00/TESTsrc" -I/TESTBUILD/pegasus/src -I"/TESTBUILD/p2.08.00/TESTCommonLib" -O -c -o /TESTBUILD/p2.08.00/TESTobj/TESTBase.o /TESTBUILD/p2.08.00/TESTsrc/TESTBase.cpp );
In file included from /TESTBUILD/pegasus/src/Pegasus/Common/Array.h:74,
from /TESTBUILD/pegasus/src/Pegasus/Common/CIMName.h:40,
from /TESTBUILD/pegasus/src/Pegasus/Client/CIMClient.h:39,
from /TESTBUILD/v2.08.00/TESTsrc/TESTVAIInterface.h:4,
from /TESTBUILD/v2.08.00/TESTsrc/TESTCaVAI.h:24,
from /TESTBUILD/v2.08.00/TESTsrc/TESTBase.h:11,
from /TESTBUILD/v2.08.00/TESTsrc/TESTBase.cpp:1:
/TESTBUILD/pegasus/src/Pegasus/Common/ArrayInter.h:49: error: redefinition of `class Pegasus::Array<Pegasus::Boolean>'
/TESTBUILD/pegasus/src/Pegasus/Common/ArrayInter.h:49: error: previous definition of `class Pegasus::Array<Pegasus::Boolean>'
In file included from /TESTBUILD/pegasus/src/Pegasus/Common/MessageLoader.h:42,
from /TESTBUILD/pegasus/src/Pegasus/Common/Exception.h:44,
from /TESTBUILD/pegasus/src/Pegasus/Common/CIMName.h:41,
from /TESTBUILD/pegasus/src/Pegasus/Client/CIMClient.h:39,
from /TESTBUILD/v2.08.00/TESTsrc/TESTVAIInterface.h:4,
from /TESTBUILD/v2.08.00/TESTsrc/TESTCaVAI.h:24,
from /TESTBUILD/v2.08.00/TESTsrc/TESTBase.h:11,
from /TESTBUILD/v2.08.00/TESTsrc/TESTBase.cpp:1:
/TESTBUILD/pegasus/src/Pegasus/Common/Formatter.h:114: error: `Pegasus::Formatter::Arg::Arg(Pegasus::Sint32)' and `Pegasus::Formatter::Arg::Arg(Pegasus::Boolean)' cannot be overloaded
In file included from /TESTBUILD/pegasus/src/Pegasus/Common/CIMProperty.h:40,
from /TESTBUILD/pegasus/src/Pegasus/Common/CIMObject.h:42,
from /TESTBUILD/pegasus/src/Pegasus/Client/CIMClient.h:41,
from /TESTBUILD/v2.08.00/TESTsrc/TESTVAIInterface.h:4,
from /TESTBUILD/v2.08.00/TESTsrc/TESTCaVAI.h:24,
from /TESTBUILD/v2.08.00/TESTsrc/TESTBase.h:11,
from /TESTBUILD/v2.08.00/TESTsrc/TESTBase.cpp:1:
/TESTBUILD/pegasus/src/Pegasus/Common/CIMValue.h:92: error: `Pegasus::CIMValue::CIMValue(Pegasus::Sint32)' and `Pegasus::CIMValue::CIMValue(Pegasus::Boolean)' cannot be overloaded
/TESTBUILD/pegasus/src/Pegasus/Common/CIMValue.h:147: error: `Pegasus::CIMValue::CIMValue(const Pegasus::Array<Pegasus::Boolean>&)' and `Pegasus::CIMValue::CIMValue(const Pegasus::Array<Pegasus::Boolean>&)' cannot be overloaded
/TESTBUILD/pegasus/src/Pegasus/Common/CIMValue.h:291: error: `void Pegasus::CIMValue::set(Pegasus::Sint32)' and `void Pegasus::CIMValue::set(Pegasus::Boolean)' cannot be overloaded
/TESTBUILD/pegasus/src/Pegasus/Common/CIMValue.h:323: error: `void Pegasus::CIMValue::set(const Pegasus::Array<Pegasus::Boolean>&)' and `void Pegasus::CIMValue::set(const Pegasus::Array<Pegasus::Boolean>&)' cannot be overloaded
/TESTBUILD/pegasus/src/Pegasus/Common/CIMValue.h:377: error: `void Pegasus::CIMValue::get(Pegasus::Sint32&) const' and `void Pegasus::CIMValue::get(Pegasus::Boolean&) const' cannot be overloaded
/TESTBUILD/pegasus/src/Pegasus/Common/CIMValue.h:409: error: `void Pegasus::CIMValue::get(Pegasus::Array<Pegasus::Boolean>&) const' and `void Pegasus::CIMValue::get(Pegasus::Array<Pegasus::Boolean>&) const' cannot be overloaded
*** Error code 1
make: Fatal error: Command failed for target `/TESTBUILD/v2.08.00/TESTsrc/TESTBase.or'
Same ERROR in Sun CC:-
palace /TESTBUILD/p2.08.00/TESTobj-> make -ef Make_SolarisVAICC TESTVAIrun
( /sun-share/SUNWspro/bin/CC -DSOLARIS_PLATFORM -DUNIX -DPEGASUS_PLATFORM_SOLARIS_SPARC_CC -features=bool -DPEGASUS_USE_EXPERIMENTAL_INTERFACES -DTEST_VAI -DEXPAND_TEMPLATES -D__EXTERN_C__ -DPEGASUS_INTERNALONLY -DPEGASUS_OS_SOLARIS -DPEGASUS_USE_EXPERIMENTAL_INTERFACES -DPEGASUS_USE_DEPRECATED_INTERFACES -Dregister= -D_POSIX_PTHREAD_SEMANTICS -DCLUSTER_GEN_APP -DSTAND_ALONE_INTEG -I"/TESTBUILD/v2.08.00/TESTsrc" -I"/Pegasus/pegasus-2.5/src" -I"/TESTBUILD/p2.08.00/TESTCommonLib" -O -c -o /TESTBUILD/p2.08.00/TESTobj/TESTBase.o /TESTBUILD/p2.08.00/TESTsrc/TESTBase.cpp );
"/Pegasus/pegasus-2.5/src/Pegasus/Common/ArrayInter.h", line 47: Error: Multiple declaration for Pegasus::Array<int>.
"/Pegasus/pegasus-2.5/src/Pegasus/Common/Formatter.h", line 103: Error: Multiple declaration for Pegasus::Formatter::Arg::Arg(int).
"/Pegasus/pegasus-2.5/src/Pegasus/Common/CIMValue.h", line 90: Error: Multiple declaration for Pegasus::CIMValue::CIMValue(int).
"/Pegasus/pegasus-2.5/src/Pegasus/Common/CIMValue.h", line 145: Error: Multiple declaration for Pegasus::CIMValue::CIMValue(const Pegasus::Array<int>&).
"/Pegasus/pegasus-2.5/src/Pegasus/Common/CIMValue.h", line 289: Error: Multiple declaration for Pegasus::CIMValue::set(int).
"/Pegasus/pegasus-2.5/src/Pegasus/Common/CIMValue.h", line 321: Error: Multiple declaration for Pegasus::CIMValue::set(const Pegasus::Array<int>&).
"/Pegasus/pegasus-2.5/src/Pegasus/Common/CIMValue.h", line 375: Error: Multiple declaration for Pegasus::CIMValue::get(int&) const.
"/Pegasus/pegasus-2.5/src/Pegasus/Common/CIMValue.h", line 407: Error: Multiple declaration for Pegasus::CIMValue::get(Pegasus::Array<int>&) const.
Thank and Regards,
DileepIn Sun C++, type bool is not equivalent to signed int. I don't think g++ makes it equivalent either.
Please show an example of source code that is causing the problem. -
Objects, Overloading, and Stock Prices
The problem - Write a program that has the following:
Data:
A string field named symbol for the Stock’s symbol.
A a string named sName for the Stock’s name.
A double field named previousClosingPrice that stores the stock’s prices form the previous day.
A double data field named currentPrice that stores the stock price for the current time.
Behaviors: (i.e. methods)
A default Constructor.
An overloaded Constructor that takes a stock with a specific symbol, name, and last closing price. ** Note values for current stock price will have to be initialized to zero.
A toString(); function that returns the current stock’s name, Symbol, and current price.
A method named getChangePercent(); that returns the percentage changed between previousClosingPrice and currentPrice.
A method named setCurrentPrice(double); that allows the setting of the current stock price.
Write a test program that creates a Stock object with the symbol ORCL, the name Oracle Corporation, and the previous closing price of 34.5.
Also, have the test program call the toString(); method to see it’s definition.
Lastly, set the new stock price to 34.35 and then display the price change percentage.
My problem is the math aspect to calculate the percentage. My result is "Infinity", which is obviously wrong. What am I missing here?
package stockPrice;
public class Stock {
//Set Data fields
public String symbol;
public String sName;
public double previousClosingPrice;
public double currentPrice = 0;
//Default Constructor
public Stock(){
//Constructor with previous closing price parameter
public Stock(String newSymbol, String newSName, double newPreviousClosingPrice) {
this.symbol = newSymbol;
this.sName = newSName;
this.currentPrice = newPreviousClosingPrice;
//Return Percent Change
double getChangePercent(){
return (((previousClosingPrice - this.currentPrice)/previousClosingPrice)*100);
//Set a new Current Price
double setCurrentPrice(double newCurrentPrice){
this.currentPrice = newCurrentPrice;
return this.currentPrice;
@Override
public String toString() {
// TODO Auto-generated method stub
String total = "The symbol is: " + this.symbol + " and the name is: " + this.sName + " and the previous closing price is: " + this.currentPrice;
return total;
}Driver:
package stockPrice;
public class Driver{
public static void main(String[] args) {
//Driver Program for all testing and Instantiation
Stock stock1 = new Stock ("ORCL", "Oracle Corporation", 34.5);
System.out.println(stock1.toString());
stock1.setCurrentPrice(34.35);
System.out.println(stock1.toString() + ". The percent change is: " + stock1.getChangePercent());
}So is setting the price as simple as this? (Keeping in mind this is my first JAVA class I am taking)...
package stockPrice;
public class Stock {
//Set Data fields
public String symbol;
public String sName;
public double previousClosingPrice = 34.5;
public double currentPrice = 0;
//Default Constructor
public Stock(){
//Constructor with previous closing price parameter
public Stock(String newSymbol, String newSName, double newPreviousClosingPrice) {
this.symbol = newSymbol;
this.sName = newSName;
this.currentPrice = newPreviousClosingPrice;
//Return Percent Change
double getChangePercent(){
return (((previousClosingPrice - this.currentPrice)/previousClosingPrice)*100);
//Set a new Current Price
double setCurrentPrice(double newCurrentPrice){
this.currentPrice = newCurrentPrice;
return this.currentPrice;
@Override
public String toString() {
// TODO Auto-generated method stub
String total = "The symbol is: " + this.symbol + " and the name is: " + this.sName + " and the previous closing price is: " + this.currentPrice;
return total;
} -
Multiple constructors for BPM Object
I need to create BPM object which can have more than one (overloaded) constructors.
Somehow I am not able to find out a way to create new constructor for a BPM object in Studio.
I guess if I create a Java class and import it in the project, it may work, but I would prefer to create a BPM object rather than java code so that I can easily modify the code as and when required.
Can someone help?Hi,
Sorry - there's no way to create multiple constructors for a BPM Object (unless as you mentioned - you create an hier from a Java jar file).
Dan
Maybe you are looking for
-
Hi, i recently got my printer about a month or so ago. It worked fine....and it printed fine... But when i try to print things out now, it wont print. I checked the networking wireless setting on the printer....on the printer it says its connected. I
-
How I can internatiolization OK and Cancel buttons confirmDialog?
private void clickButton() { int response = JOptionPane.showConfirmDialog(this, resBundle.getString("Confirmation_text_itroduction"), resBundle.getString("Confirmation_title"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.Q
-
Does the Ipod touch third generation have an international power supply?
does the Ipod touch third generation have an international power supply? Am going to travel in Europe and want to know if I need to use a convertor with it or if it has the international power supply and I can get by with the appropriate plug adapte
-
Add Plant, item and PO number to tcode FAGLL03 as display option
Hi All, Please explain me the ways to include PLANT, ITEM and PO number in the standard report display. The transaction code is FAGLL03. It will display the GL line items and using 1SAP-Standard layout, there is no way to select PO number and ITE
-
Fill Image not visible with iOS (ipad/iphone)
Hi I created a website with Adobe Muse and I have an issue when surfing with ipad or iphone. When you have a coloured rectangle and add a fill image to it, it's perfectly visible with any type of browser on a desktop pc. Yet, when using iOS7 the imag