I am writing small pieces of code just to practice for the exam and came up with the following question. I understand you can call the super() version of an overridden method from a method in the subclass. Is there a way to do it directly from an instance variable of the subclass? The following does not work:
I haven't seen anything like this so I assume I would have to write a new method in SubClass to call the SuperClass method. Thanks!
Calling super() invokes either the default or no-arg constructor for the super class. A constructor's purpose in life is to initialize it's object. So it really only makes sense to call super() when the object is being instantiated. Therefore, the only place you can explicitly call super() is from within a constructor in the subclass. And then you had better be sure that either A) no other constructor has been declared on the super class thereby letting the compiler add the default constructor or B) the no-arg constructor has been explicitly declared on the super class.
So, the constructor is not really a method. Constructors have lots of rules specific to them. You can think of it as a special kind of method with its own rules if you want. But it's definitely not a method.
Kendall Ponder wrote:Is there a way to do it directly from an instance variable of the subclass?
No, you can't!
As already mentioned by Douglas, you can use super() only to invoke constructor from the superclass and this() to invoke an overloaded constructor as shown in the following code snippet:
Kendall Ponder wrote:I haven't seen anything like this so I assume I would have to write a new method in SubClass to call the SuperClass method.
That's indeed a possibility. But you have to be careful and invoke this method using the super keyword, like Jeanne has suggested. Otherwise you still would invoke the method() method in SubClass. Illustrated with this code snippet:
Another possibility would be to refactor the SuperClass class a little bit: you define an additional final method (subclasses can't override this method) which has the println-statement; the current method() method simply invokes this final method. As shown in this code snippet: