Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Access the superClass' toString()?
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Zren




PostPosted: Thu Mar 05, 2009 1:36 am   Post subject: Access the superClass' toString()?

Is there a way to access the toString of a superClass? Or when you make a toString() class in the subClass, do you completely overwrite it?

I know super.toString() doesn't work since it's like it makes a new instance without loading the constructor class.
Sponsor
Sponsor
Sponsor
sponsor
wtd




PostPosted: Thu Mar 05, 2009 1:55 am   Post subject: RE:Access the superClass\' toString()?

code:
chris@spectrum:~$ cat Test.java
class Foo {
        public String toString() {
                return "Foo";
        }
}

class Bar extends Foo {
        public String toString() {
                return "Bar";
        }

        public String superString() {
                return super.toString();
        }
}

public class Test {
        public static void main(String[] args) {
                Bar a = new Bar();

                System.out.println(a.toString());
                System.out.println(a.superString());
        }
}
chris@spectrum:~$ javac Test.java
chris@spectrum:~$ java Test
Bar
Foo
chris@spectrum:~$
DemonWasp




PostPosted: Thu Mar 05, 2009 1:56 am   Post subject: RE:Access the superClass\' toString()?

super.toString() actually does what you want. See here: http://java.sun.com/docs/books/tutorial/java/IandI/super.html

You're thinking of super(), which calls the constructor of the parent class explicitly - something completely different.
Zren




PostPosted: Thu Mar 05, 2009 10:20 am   Post subject: Re: Access the superClass' toString()?

Weird, the first time I did this, all the values from the superClass were null, so I thought...ya. Turns out I had two other methods with the same name that I called from the constructor. So if a method has a same name in as one of it's subClass methods, is their any way to access it, or is it just dubbed lazy and bad programming?

Thanks WTD for the example.
DemonWasp




PostPosted: Thu Mar 05, 2009 11:40 am   Post subject: RE:Access the superClass\' toString()?

The Java language doesn't appear to specify any such method. Really, if you're relying on X method not to change its behaviour in a subclass, you should declare it as final so it can't be overridden.
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 5 Posts ]
Jump to:   


Style:  
Search: