• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Private methods overriden in a Sub class

 
Ransika deSilva
Ranch Hand
Posts: 524
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
Could you please tell me is it possible to override private methods of the super class, from sub class.
Thank you..
 
santoshsamala kumar
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes we can override a private method of superclass
I have tried with the following program
class superclass
{
int x=10;
private void supermethod()
{
this.x=x;
System.out.println("this is the method of super class"+x);
}
}
class Base extends superclass
{
int a=20,b=30;
void supermethod()
{
this.a=a;
this.b=b;
System.out.println("this is the method of subclass"+a+"-"+b);
}
}
public class Forum1
{
public static void main(String args[])
{
System.out.println("in main class");
Base b=new Base();
b.supermethod();
}
}
and successfully run the output is:
in main class
this is the method of subclass20-30
but one caution:You cant override static method
 
Ransika deSilva
Ranch Hand
Posts: 524
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, I am agreeing with you too. But what I don't understand is, private means, the visibility is restricted to the class it self isn't it?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The example you've shown shows that you can define a method of the same name as a method in the superclass. This isn't necessarily the same as overriding the method. Try this: add a method "callSupermethod()" to superclass like this:

Then in your main program, create an instance of Base and invoke callSupermethod() on it. What gets printed out? Does this surprise you?
Even though you've "overridden" the method in Base, callSupermethod() will still invoke the version in superclass, not the new one in Base, because although you've provided a new definition, it's not really overriding.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic