Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritance of private method ?

 
Viktor Kubinec
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4568
9
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 10527
64
Eclipse IDE Hibernate Ubuntu
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Viktor Kubinec
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot for quick and accurate answers ;)
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic