We use the keyword super to call the superclass version of an overridden method for eg,
[B] [/B] the above file is saved as Dog.java it gives a compiler error stating that non static variable super cannot be referenced from a static context super.dostuff(); ^ what does this mean??
The main method is static, and it can only call other static methods and is not allowed to refer to super or even 'this' for that matter, so you'll find you can't even call Dog's doStuff without an instance. You could call that super.doStuff method from the child's doStuff method. You could also create some other a non-static method that makes that call, but then you need an instance of the class so that you can call that method.
You would usually call super.foo() from inside the overridden foo() method, which means you are using the original (superclass = un-overridden) functionality inside the overridden method. Example in a very commonly overridden methodThat will return whatever the Bar toString method returns, with " Foo" at the end.
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32839
4
posted
0
This bit about "non-static . . . cannot be . . . from a static context" is a very common mistake.
You have a static method, which belongs to the class; there is only one copy of that method anywhere in memory. You have an instance member, which belongs to the object, so there might be several copies of it, with different values in. Which of those are you calling? So the compiler won't allow access. The keywords super and this refer to objects, so they are regarded rather as instance variables, so the compiler won't allow access from a static context either.
You can only call super when you're overriding methods. As said before in one of your other threads, static methods are not overridden but redefined. As such, super is not allowed.
Since the method is static, you can just call Animal.doStuff inside Dog.doStuff.