Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: Overriding Object's toString() method outside of their class

  1. #1
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Overriding Object's toString() method outside of their class

    I have an odd question. Basically, I'm wanting to know if I can temporarily override an object's toString() method inside another class.

    For example, if I had two classes (Object1 and Object2). Object1 contains a List of Object2s, and I'm wanting to print out the List of Object2s' var values using only the toString() method, and without overriding it in the Object2 class. So I would have code similar to this (before solving my problem):
    public class Object1 {
    	List<Object2> list;
    	public Object1(List<Object2> toAdd) {
    		list = toAdd;
    		for(Object2 obj : list) {
    			System.out.println(obj);
    		}
    	}
    }
     
    public class Object2 {
    	int var;
    	public Object2(int n) {
    		var = n;
    	}
    }

    I have no idea if this code will compile, and there is no main, but the concept is obvious. Does anyone know if it is possible?
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/


  2. #2
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: Overriding Object's toString() method outside of their class

    I also haven't attempted to compile that code, but it looks OK. In particular you can say System.out.println(obj): println() will have a go at printing anything you throw at it!

    Basically, I'm wanting to know if I can temporarily override an object's toString() method inside another class.

    For example, if I had two classes (Object1 and Object2). Object1 contains a List of Object2s, and I'm wanting to print out the List of Object2s' var values using only the toString() method, and without overriding it in the Object2 class.
    This is a bit confusing. You begin with the desire to "temporarily override" but end with the restriction "without overriding". It might be easier to forget *how* you do what you want to do and focus on *what* you want to print: to override or not to override is not the question.

    I'm assuming you want to print the decimal form of a bunch of int values. Possibly with some formatting: {42, 0, 666, -1} (or possibly not)

    println() is going to use the toString() of its argument (unless it is null... See the API docs for details.) And, in general, absolutely anything you do from another class will involve using the accessible (let's say "public") methods exposed by the Object2 class. Exposing behaviour in a limited, controlled way, is the raison d'être of using classes. That's a pretty broad claim! but I deliberately stop short of saying you *should* do it that way. The point is only that the Java language does it that way and it will be hard and unrewarding work to fight the language. (a better option is to use another)

    In the particular case you posted var has no access modifier. So depending on the package structure you might "get away" with

    System.out.println(obj.var + " ");

    However unless you really mean var to have default access it would be better for callers to use the exposed behaviour of the Object2 class. If it does not suit you to override its toString() then Object2 should expose some other behaviour:

    public String toDisplayForm() {
        return "" + var;
    }

    which can then be used caller:

        // caller provides the formatting
    boolean first = true;
    for(Object2 obj : list) {
        if(first) {
            System.out.print("{");
            first = false;
        } else {
            System.out.print(", ");
        }
            // the thing called provides the display form
        System.out.println(obj.toDisplayForm());
    }
    System.out.println("}");
    Last edited by pbrockway2; May 11th, 2012 at 06:38 PM.

  3. #3
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Overriding Object's toString() method outside of their class

    Actually, the real-world implementation of this is I have an Object, whose toString() method is used throughout various parts in the program. In this new class, I am adding the object to a JTree (which displays Objects by calling their toString() method like almost all of the swing objects), but the current toString() method that the Object has that is used everywhere else in the program is not adequate enough for this particular panel. I figured explaining all of this would be too convoluted for a problem that can easily be expressed in a simple code like the one I posted above.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  4. #4
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: Overriding Object's toString() method outside of their class

    It might be worth having a read of How To Use Trees in Oracle's Tutorial.

    The data contained in a JTree instance is contained in a corresponding TreeModel instance and even when we don't work with that instance directly "adding an object to a tree" will involve interaction with the tree model. The Tutorial illustrates how user objects might be "wrapped" in an instance of DefaultMutableTreeNode. The Tutorial comments "The argument to the DefaultMutableTreeNode constructor is the user object which is an object that contains or points to the data associated with the tree node. The user object can be a string, or it can be a custom object. If you implement a custom object, you should implement its toString method so that it returns the string to be displayed for that node. JTree, by default, renders each node using the value returned from toString, so it is important that toString returns something meaningful."

    The last sentence may be what you are up against. (just guessing without seeing the code) If so what follows is significant: "Sometimes, it is not feasible to override toString; in such a scenario you can override the convertValueToText of JTree to map the object from the model into a string that gets displayed."

    Even more fine tuned control over what appears in the tree corresponding to some object of data is provided by customising the tree's renderer which is illustrated in the section "Customizing a Tree's Display".

    -----

    Either way the object representing the data can cooperate in the process by providing a public method, distinct from its toString(), which returns a suitable readable form if that s appropriate. With Swing, as in my previous post, the tree (with its renderer and any logic that can be sensibly put in convertValueToText()) provides the formatting while the object provides the textual data to be displayed.
    Last edited by pbrockway2; May 11th, 2012 at 10:27 PM.

  5. #5
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Overriding Object's toString() method outside of their class

    You can't "temporarily" override a method, and I don't know of any way to override a method from another class.

    Probably the most versatile and simplest solution I can think of is to create your own TreeCellRenderer class.

  6. #6
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Overriding Object's toString() method outside of their class

    pbrockway2, the only thing I can think that would be problematic is that the JTree contains several different Objects, so just overriding the convertValueToText might not work. I'll try doing it with an instanceof check or something and get back to you.


    So I was just sorta playing around, and I figured out something close that works, although I believe it just automatically creates a new Object that extends from the other. An example is:
    public static void main(String[] args)
    	{
    		int month, year;
     
    		//February
    		month = 1;
    		//Year 2004
    		year = 2004;
     
    		GregorianCalendar cal = new GregorianCalendar(year,month,1) {
    			public String toString() {
    				return "Method Override.";
    			}
    		};
    		System.out.println(cal.toString());
    	}
    Last edited by aussiemcgr; May 12th, 2012 at 08:36 AM.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  7. #7
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Overriding Object's toString() method outside of their class

    Yes, that code creates an Anonymous class which extends the GregorianCalendar class.

  8. #8
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Overriding Object's toString() method outside of their class

    Quote Originally Posted by aussiemcgr View Post
    Actually, the real-world implementation of this is I have an Object, whose toString() method is used throughout various parts in the program. In this new class, I am adding the object to a JTree (which displays Objects by calling their toString() method like almost all of the swing objects), but the current toString() method that the Object has that is used everywhere else in the program is not adequate enough for this particular panel. I figured explaining all of this would be too convoluted for a problem that can easily be expressed in a simple code like the one I posted above.
    Any reason why you can't just create a wrapper class which wraps the Object of interest and returns the appropriate String value for the JTree, then add these to the JTree?

  9. #9
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Overriding Object's toString() method outside of their class

    copeg, when the user selects an object in the JTree, it is going to update a form to the right of it with the information of the object the user selected. How would a wrapper class effect my ability to get the object that was selected? There is a possibility that the String representation of the object may be the same for several objects in the JTree.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  10. #10
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Overriding Object's toString() method outside of their class

    The wrapper object would contain the original object, just create a method that would direct you to that object.

  11. #11
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Overriding Object's toString() method outside of their class

    Here is a simple, generalized, undocumented wrapper class that I just improvised which demonstrates using a wrapper class to allow different String's to be returned by the toString method depending upon how one implements the Convertable interface. Clients can get the wrapped object using the getUserObject method (should compile although I didn't test it directly)

    /**
    *
    * @author copeg
    */
    public class Wrapper<T>{
        private final T wrapped;
        private final Convertable converter;
        public Wrapper(T t, Convertable c){
            this.wrapped = t;
            this.converter = c;
        }
     
        public Wrapper(T t){
            this(t, null);
        }
     
        public T getUserObject(){
            return wrapped;
        }
     
        @Override
        public String toString(){
            if ( converter == null ){
                return wrapped.toString();
            }
            return converter.convert();
        }
     
     
    }
    /**
    *
    * @author copeg
    */
    public interface Convertable{
        public String convert();
    }

  12. #12
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: Overriding Object's toString() method outside of their class

    Quote Originally Posted by copeg View Post
    Any reason why you can't just create a wrapper class which wraps the Object of interest and returns the appropriate String value for the JTree, then add these to the JTree?
    I can't think of any reason. But isn't DefaultMutableTreeNode just such a wrapper?... As discussed above.

    Its toString() returns the toString() of the wrapped object for display in a simple tree, behaviour which can be overridden (at the time the object is added to the tree, thereby removing the need for any nasty "instanceof" later.)

Similar Threads

  1. Java Class : How do I set up a toString method for arrays?
    By red7 in forum What's Wrong With My Code?
    Replies: 10
    Last Post: May 11th, 2012, 05:47 PM
  2. Replies: 1
    Last Post: February 12th, 2012, 01:01 AM
  3. Advantages of method Overloading and Overriding
    By tcstcs in forum Java Theory & Questions
    Replies: 2
    Last Post: January 19th, 2012, 04:55 AM
  4. [SOLVED] ArrayList object's elements confusing??? doesnt replace the elements? set() method?
    By chronoz13 in forum What's Wrong With My Code?
    Replies: 10
    Last Post: June 21st, 2011, 01:20 PM
  5. Object as a Reference into Object's Class
    By Ace Coder in forum Object Oriented Programming
    Replies: 6
    Last Post: November 30th, 2010, 12:22 PM