File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes public and private inheritance in Java like in C++? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "public and private inheritance in Java like in C++?" Watch "public and private inheritance in Java like in C++?" New topic

public and private inheritance in Java like in C++?

Timothy Sam
Ranch Hand

Joined: Sep 18, 2005
Posts: 751
Although I don't understand the us of it, there's this thing called public inheritance in C++ that goes like this...

I've been hooked up with Java for quite sometime but never encountered this... I just thought of this when I was doing some reading with C++. Anyone? Thanks!
[ March 23, 2006: Message edited by: Timothy Sam ]

SCJP 1.5
Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
Java only has public inheritance. That is, you both inherit implementation and interface.

With private inheritance, you would only inherit implementation. It's basically a more static form of composition, as far as I remember.

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
Of course, when comparing Java to C++ we are talking analogies, but public derivation in C++ is analogous to Java's sole inheritance mechanism. Where it gets funky is with other forms of inheritance in C++, like private:

class Dog : private Animal {...}

This is closest to Dog having a private Animal field:

Because the C++Dog is derived from Animal it can access its protected animal parts (dogs do that, eh), so the match isn't perfect. There is also 1 piece of C++ syntax that I can't recall the details of, perhaps it is written:

public: Animal::foo;

That lets you reexpose Animal methods in Dog that would otherwise be hidden. In Java you delegate:

public void scratch() {sooper.scratch();}

There is also protected derivation:

class Dog : protected Animal

which is closest to making that sooper field being protected instead of private.

Again, this is all a rough analogy. Perhaps the crux of the matter is which language is better served by its derivation mechanism. In C++ private derivation ("implementation derivation") is praised for being more efficient than using delegation. In Java those sorts of concerns seem to be passed off to hot-spot optimization.

There is no emoticon for what I am feeling!
I agree. Here's the link:
subject: public and private inheritance in Java like in C++?
It's not a secret anymore!