CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    May 2013
    Posts
    4

    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 :

    stock.Stock@517667bd

    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() {
    noOfShares=0;
    tickerSymbol="[UA]";
    dividend=0.0;
    }
    public Stock(int inNoOfShares,String inTickerSymbol,double inDividend)
    {
    System.out.println("label");
    noOfShares = 10;
    tickerSymbol="firstticker";
    dividend = 23;
    }
    public Stock(int inNoOfShares,double inDividend)
    {
    noOfShares=20;
    tickerSymbol="Secondticker";
    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);
    System.out.println(stockOne);

    }
    }

  2. #2
    Join Date
    Jun 2011
    Posts
    12

    Re: Calling a Constructor results in unexpected output

    Works as expected. I get following output:
    ------------------
    label
    Stock@9304b1
    ------------------

    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.

    http://www.javabeginner.com/learn-ja...ostring-method

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured