Calling a Constructor results in unexpected output
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums
Results 1 to 2 of 2

Thread: Calling a Constructor results in unexpected output

  1. #1
    Join Date
    May 2013

    Question Calling a Constructor results in unexpected output

    Hi All,

    I have created a Class named Stock and have declared three Constructor . First constructor with no parameter, second constructor with three parameter, third with Two parameter.

    When I call my constructor inside a System.out.println(constructor); , it should display the variable Values right ? . but instead it outputs default toString Value.

    Please explain this behaviour.

    output :


    ouput im expecting is (as per the book im referring)

    20 sa 4.0

    my code is as follows :

    // this is the Stock class which has constructors

    public class Stock {

    private int noOfShares;
    private String tickerSymbol;
    private double dividend;

    public Stock() {
    public Stock(int inNoOfShares,String inTickerSymbol,double inDividend)
    noOfShares = 10;
    dividend = 23;
    public Stock(int inNoOfShares,double inDividend)
    dividend = 46;


    // this is application program used to test the above class

    import stock.Stock;

    public class StockTest {

    public static void main(String[] args) {
    int noOfShares;
    String tickerSymbol;
    double dividend;

    Stock stockOne ;
    Stock stockTwo ;
    Stock stockThree ;

    stockOne = new Stock(20,"sa",4.0);


  2. #2
    Join Date
    Jun 2011

    Re: Calling a Constructor results in unexpected output

    Works as expected. I get following output:

    When you create the object with these arguments the constructor prints the label and assigns variables and then prints out the reference ID to the object. You have to either override the default toString method in your class (seems more logical thig to do) or add a println method to the constructor which prints out the variables and loose the System.out.println(stockOne); line.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)