• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriding Methods!!!!!

 
sam patel
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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");
}
}
regards,
Saumil Patel
 
sun par
Ranch Hand
Posts: 257
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey MyClass2 should extend from MyClass. Anyway,
To override means polymorphism.
There is no polymorphic behaviour because if you add
mc=mc2;
mc.myMethod();

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.
 
sam patel
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you soo much for your replys...
I got it now...
Again thanks..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic