Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Override Method...

 
RAGU KANNAN
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

The bellow is one of the rules for overriding a method.
�The access level can be less restrictive than that of the overridden method.�

If I try to run the following class it gives the error message. Pls let me know what am I missing.
�Over.java :14: amethod(int) has private access in Base0.amethod(iBase);�




class Base
{
private void amethod(int iBase)
{
System.out.println("Base.amethod()");
}
}
class Over extends Base
{
public static void main(String argv[])
{
Over o = new Over();
int iBase = 0;
o.amethod(iBase);
}
public void amthod(int iOver)
{
System.out.println("Over.amethod()");
}
}
 
shilpa Reddy
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public void amthod(int iOver)
there is a spelling mistake it shud be amethod......
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
private methods are not visible in subclasses, so they cannot be overridden.

With the typo corrected, this code should work. However, it's still not overridding the method -- it's just calling the method defined in Over.

The error message you posted would occur if the variable 'o' were defined as type Base, because then you would be trying to access a private member from outside the class.
 
Milind Patil
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ragu,

If check the code you have given, Base class's private method and child class's method name are different. You are using base class's instance to call super class's method which is actually private to super class.
That's why you are getting this error.

If you modify you base class's method signature then there wont be any proble executing your code.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic