aspose file tools*
The moose likes Beginning Java and the fly likes Private methods overriden in a Sub class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Private methods overriden in a Sub class" Watch "Private methods overriden in a Sub class" New topic
Author

Private methods overriden in a Sub class

Ransika deSilva
Ranch Hand

Joined: Feb 18, 2003
Posts: 524
Hello,
Could you please tell me is it possible to override private methods of the super class, from sub class.
Thank you..


SCJP 1.4, SCMAD 1.0<br />SCWCD, SCBCD (in progress)
santoshsamala kumar
Greenhorn

Joined: Nov 02, 2003
Posts: 3
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

Joined: Feb 18, 2003
Posts: 524
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

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Private methods overriden in a Sub class