Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes Inheritance of private method ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Inheritance of private method ?" Watch "Inheritance of private method ?" New topic
Author

Inheritance of private method ?

Viktor Kubinec
Ranch Hand

Joined: Jan 28, 2012
Posts: 34
Hello,

i am preparing for java SE certification exam and playing a little bit with the code. From the theory :
- private methods are not inherited (and therefore cannot be overriden)
- non static class methods cannot be executed without instance of the class

in this sample code I have Parent and Child classes, Parent has a private method test(), Child extends Parent, but since the only non static method in Parent class is private, Child doesn't inherit it. In the Parent's main method I execute test() method on reference (type Parent), which reffers to Child instance. How is it possible that Parent's test() method is executed without instance of Parent?

Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4425
    
    8

Hi Viktor. Welcome to The Ranch!

It's not true that a private method is not inherited. It just isn't visible to the subclass. But as you've demonstrated, it can be called if it is visible.

I'd avoid ever doing that in practice, though. It's fine for trying things out, but it's a poor design for a superclass to know anything about its subclasses.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8049
    
  22

Viktor Kubinec wrote:How is it possible that Parent's test() method is executed without instance of Parent?

But you do have an instance of Parent. You made one with the line:
Parent p = new Child();

What you could NOT do is write:
Child p = new Child();
p.test();


HIH

Winston


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
Viktor Kubinec
Ranch Hand

Joined: Jan 28, 2012
Posts: 34
Thanks a lot for quick and accurate answers ;)
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Matthew Brown wrote:
It's not true that a private method is not inherited.


Sorry, but it is true.

From JLS 8.2 Class Members: "Members of a class that are declared private are not inherited by subclasses of that class."
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Winston Gutkowski wrote:
But you do have an instance of Parent.


@Victor: Just to clarify a bit: What Winston says here is correct, but make sure you understand that you have ONE object. That object IS A Child, IS A Parent, IS AN Object, and IS A whatever other classes it extends or interfaces it implements.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Inheritance of private method ?