Results 1 to 2 of 2
  1. #1
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default using constructors

    I am trying to initialize variables with a constructor. after trying this code, i get some weird output. here is my code:

    Java Code:
    public class musicalNote {
    
    	 musicalNote(int a, String hi) {
    		String x = "B";
    	}
    	
    	public static void main(String args[]) {
    	
    		musicalNote x = new musicalNote(72, "whole");
    		System.out.println(x);
    	
    	}
    and the output:

    Java Code:
    musicalNote@addbf1
    do i understand constructors, correctly? i understand that i can't return a value with a constructor.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: using constructors

    Quote Originally Posted by droidus View Post
    I am trying to initialize variables with a constructor. after trying this code, i get some weird output. here is my code:

    Java Code:
    public class musicalNote {
    
    	 musicalNote(int a, String hi) {
    		String x = "B";
    	}
    	
    	public static void main(String args[]) {
    	
    		musicalNote x = new musicalNote(72, "whole");
    		System.out.println(x);
    	
    	}
    A problem I see immediately with the code above is that the constructor completely ignores the parameters that are passed to it.

    and the output:

    Java Code:
    musicalNote@addbf1
    This output is the expected output since your class does not override the toString() method. If you put in a decent override for this method, your println will make a whole lot more sense.

Similar Threads

  1. Need help with constructors
    By tpfaff in forum New To Java
    Replies: 10
    Last Post: 10-22-2010, 04:33 AM
  2. Constructors
    By suresh.sa in forum New To Java
    Replies: 5
    Last Post: 10-20-2010, 12:10 AM
  3. constructors?
    By shroomiin in forum New To Java
    Replies: 4
    Last Post: 10-13-2009, 02:14 PM
  4. Constructors
    By new2java2009 in forum New To Java
    Replies: 5
    Last Post: 08-18-2009, 06:46 AM
  5. constructors
    By khamuruddeen in forum New To Java
    Replies: 2
    Last Post: 12-01-2007, 03:15 PM

Posting Permissions

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