Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriding private functions

 
Cristian Negresco
Ranch Hand
Posts: 182
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 182
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
It helped, thanks.
Cristian
 
juan Tsui
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi:
All ,the question and the answer are very well. I am implicit with these .
Thanks All .
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic