Rendelle Fox wrote:
Obviously, this must be the intended functionality of Java, but am I the only one surprised by that? The parent function will actually call the child's function before its own? What do I do if I want (which I do) the parent foo just to call its own version of bar? (this.bar() does not make any difference).
The super.foo(); call in the subclass calls the superclass method. But notice what happens. The getClass() invocation returns the SubClass object, and the bar() method returns sub-bar. you are getting the overridden methods from the subclass.
[campbell@campbell1110 java]$ javac SuperClass.java
[campbell@campbell1110 java]$ java SuperClass
SuperClass foo super-bar
SubClass foo sub-bar
Rendelle Fox wrote:I had thought I understood all about polymorphism and overriding methods. I mean, of course if I call c.bar() I expect to see c's bar which may or may not call the parent's bar as well, depending on how it is written. I just don't think I ever encountered the situation where you override a function that the parent class is calling somewhere, and that breaks the parent class. (Or maybe I just assumed something elsewhere was calling it - like if you override paintComponent and forget to call super, I knew that would break things).
The thing is, I want to have both ParentClass and ChildClass with a foo (this is actually my constructor in my real program) and a bar. I need ParentClass to be able to act on its own, so it needs both. But I also want ChildClass to override both. So are you saying that is it simply not possible to force a particular call to bar within the parent's foo to call its own bar, even if it has been overridden?
. . . so you see, I am a cruel so-and-so who kicks dogs. Also that the constructor and instance methods both call other methods polymorphically. You can try changing the visibility of the makeNoise method to private and see what happens. I said yesterday you should mark any methods called from your constructor private (or final, which I forgot). Otherwise, you might not be breaking your class, but you are getting behaviour you hadn't expected. I would reserve "breaking the class" for instances where the class invariants are breached.
[campbell@campbell1110 java]$ java Menagerie
Newborn Catt: Miaow! Purrrrr! Meow
Newborn Dog: Woof! Woof!
Newborn Animal: Uggggh!
Catt kicked: Spit! Sssssssssssszzss
Dog kicked: Grrrrrrrrrrrrrrrr!