round up

Stephanie Grasson

Ranch Hand

Posts: 347

posted 17 years ago

This question is about Rule Roundup question #20. The question reads: Can a private method of a superclass be declared within a subclass? The answer is yes and the reasoning is as follows: Private methods can NOT be overridden, but they CAN be redeclared/redefined in the subclass, and called directly on the subclass object. But polymorphism will not apply. Can anyone provide an example of this? I am a little unclear as to why one would ever want to do this. Thanks!

in above program both doc1 & doc2 point to a TribalDoctor Object. but in first case the superclass dance() is called while in second case subclass function is called. had the function dance be declared as public. then both the function calls would have called sub class function. i think this example clears where this is used ----- in above example. a tribal doctor may dance like a tribal person if he is among tribals. or can dance like tribaldoctor when he is among tribaldoctors.

regards deekasha

Shafeeq Sheikh

Ranch Hand

Posts: 68

posted 17 years ago

Deekasha..... Your code above does not compile.... It gives an error saying: C:\java\bin>javac TribalDoctor.java TribalDoctor.java:19: No method matching dance() found in class TribalPerson.doc1.dance(); ^ 1 error Since the dance method is private, you cannot access it from any other class. As the answer on the Java ranch mock exam says: Private methods can NOT be overridden, but they CAN be redeclared/redefined in the subclass, [/b]and called directly on the subclass object. But polymorphism will not apply [/b]. You will not be able to call the dance method of the superclass from the child class. On the other hand you CAN call the dance method of the child class from the child class. Note that doc1 above is of type TribalPerson. Please correct me if I'm wrong.....

thomas

Ranch Hand

Posts: 79

posted 17 years ago

I think Shafeeq is right. Make the following changes to Deekasha's code: 1. Make the dance() method public in the TribalDoctor class 2. move the main() method to the TribalPerson class You should be able to compile and run. doc1.dance() will make the tribal person dance and doc2.dance() will make the tribal doctor dance!

Anonymous

Ranch Hand

Posts: 18944

posted 17 years ago

A very simular question was on the SCJP2 exam. So spend some time learning this concept if yor do not understand it. Monty6