GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overriding private functions 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 private functions" Watch "Overriding private functions" New topic
Author

Overriding private functions

Cristian Negresco
Ranch Hand

Joined: Sep 15, 2001
Posts: 182
Hi,
This is from JQPlus free mock exam:
class SuperClass
{
public void methodA()
{
System.out.println("In superclass's method A");
methodB(); //0
}
private void methodB()
//public void methodB()
{
System.out.println("In superclass's method B");
}
}
class SubClass extends SuperClass
{
public void methodB()
{
System.out.println("In subclass's method B ");
}
public static void main(String args[])
{
SuperClass obj = new SubClass();
obj.methodA();
}
}

1.Is it so that is not possible to override private functions?
2.Is there a way in which I can call the SubClass methodB - just curiosity?
Ferry Widjaja
Greenhorn

Joined: Oct 25, 2001
Posts: 15
I dont think so ,
private = only visible to the current class
You cant access it in anyway
You might think of overriding it but you actually
creating a new method in the SubClass
please correct me if I am wrong
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Hi Cristian,
No you can't override a private method. Since the subclass doesn't even see the method it can't replace it. If you call methodB from SuperClass methodA it only sees its own private method. Therefore, from SuperClass methodA you can not call SubClass methodB.
However, if in the SubClass main you create a SubClass reference variable then you can call its' methodB class.
Example:

Regards,
Manfred.
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
No, you cannot override any final, static and private methods.
Coming to your second question...

*1*, *2* can solve your problem.

Hope this helps
Shyam
Cristian Negresco
Ranch Hand

Joined: Sep 15, 2001
Posts: 182
Hi all,
It helped, thanks.
Cristian
juan Tsui
Greenhorn

Joined: Oct 26, 2001
Posts: 13
Hi:
All ,the question and the answer are very well. I am implicit with these .
Thanks All .
 
GeeCON Prague 2014
 
subject: Overriding private functions