File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overriding Methods!!!!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overriding Methods!!!!!" Watch "Overriding Methods!!!!!" New topic

Overriding Methods!!!!!

sam patel
Ranch Hand

Joined: Jun 13, 2002
Posts: 103
I read couple of places where they say
You cannot override a private or a final method.
I understand about the final method...
But i am confused about the Private...
Tell me if i wrong about this...
public class MyClass{

private void myMethod(){
System.out.println("Private myMethod in MyClass");

public static void main(String args[]){
MyClass mc = new MyClass();
mc.myMethod(); // prints "Private myMethod in MyClass"
MyClass2 mc2 = new MyClass2();
mc2.myMethod(); // prints "Protected myMethod in MyClass2"
class MyClass2{
protected void myMethod(){
System.out.println("Protected myMethod in MyClass2");
Saumil Patel
sun par
Ranch Hand

Joined: Oct 03, 2002
Posts: 257
if you have a private method in a base class, and then you have a derived class in which you have the same method, what happens is since the private method is not visible in the derived class it treats the method as a new method ... in that case it is not an overridden method...

meth in class A is not accessible in class B and hence the method in class B is not an ovberidden method, but is treated as a new method

Sunita<br />SCJP 1.4
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
Hey MyClass2 should extend from MyClass. Anyway,
To override means polymorphism.
There is no polymorphic behaviour because if you add

you will see that the private message is printed, not the one corresponding the real type of the object (MyClass2) pointed to by mc.
Try deleting private and the message "Protected myMethod in MyClass2" will be printed.

SCJP2. Please Indent your code using UBB Code
sam patel
Ranch Hand

Joined: Jun 13, 2002
Posts: 103
Thank you soo much for your replys...
I got it now...
Again thanks..
I agree. Here's the link:
subject: Overriding Methods!!!!!
jQuery in Action, 3rd edition