How to... private inheritance ?!

S

sakis.panou

Hi all,

Apologies if the subject has been already discussed but I have been
unable to find what I am looking for. My background is predominantly C+
+ and while I have been trying to familiarise myself with Java I have
come across something I can't get my head around.

In C++ one can create an interface through a pure abstract class then
derive from that interface privately, whilst providing concrete
implementation of the methods exposed by the interface. The reason one
might want to implement a private inheritance is to force the user of
the concrete class to cast it to the interface without allowing them
to access the interface's methods through the concrete class itself.

Here is an example of how this works in C++:

class IWindow
{
public:
void openWindow( void ) = 0;
void closeWindow( void ) = 0;
}

class Car: IWindow
{
private:
void openWindow( void ) {};
void closeWindow( void ) {};
}

Car theCar;
IWindow* pCarWindow = reinterpret_cast<IWindow*>(&theCar);

pCarWindow->openWindow();
pCarWindow->closeWindow();

I am fully expecting some folk not to like the idea of private
inheritance in C++ and that is more than fair, but it works really
well especially when you really want to enforce the users of the
concrete class not to use the interfaces's methods directly from the
concrete class's instance.

So my question is how do I achieve the same in Java ? Any help of
suggestions would be truly appreciated.

Kind Regards,
Sakis
 
A

Arne Vajhøj

In C++ one can create an interface through a pure abstract class then
derive from that interface privately, whilst providing concrete
implementation of the methods exposed by the interface. The reason one
might want to implement a private inheritance is to force the user of
the concrete class to cast it to the interface without allowing them
to access the interface's methods through the concrete class itself.

Here is an example of how this works in C++:

class IWindow
{
public:
void openWindow( void ) = 0;
void closeWindow( void ) = 0;
}

class Car: IWindow
{
private:
void openWindow( void ) {};
void closeWindow( void ) {};
}

Car theCar;
IWindow* pCarWindow = reinterpret_cast<IWindow*>(&theCar);

pCarWindow->openWindow();
pCarWindow->closeWindow();

I am fully expecting some folk not to like the idea of private
inheritance in C++ and that is more than fair, but it works really
well especially when you really want to enforce the users of the
concrete class not to use the interfaces's methods directly from the
concrete class's instance.

So my question is how do I achieve the same in Java ?

I don't think you can.

Java does not permit that kind of subtleties.

Arne
 
M

Mike Schilling

Hi all,

Apologies if the subject has been already discussed but I have been
unable to find what I am looking for. My background is predominantly
C+ + and while I have been trying to familiarise myself with Java I
have come across something I can't get my head around.

In C++ one can create an interface through a pure abstract class then
derive from that interface privately, whilst providing concrete
implementation of the methods exposed by the interface. The reason one
might want to implement a private inheritance is to force the user of
the concrete class to cast it to the interface without allowing them
to access the interface's methods through the concrete class itself.
Here is an example of how this works in C++:

class IWindow
{
public:
void openWindow( void ) = 0;
void closeWindow( void ) = 0;
}

class Car: IWindow
{
private:
void openWindow( void ) {};
void closeWindow( void ) {};
}

Car theCar;
IWindow* pCarWindow = reinterpret_cast<IWindow*>(&theCar);

pCarWindow->openWindow();
pCarWindow->closeWindow();

I'm missing something. Why is is better to do the (unsafe) case before
calling the methods than to call them directly?
 
J

Joshua Cranmer

In C++ one can create an interface through a pure abstract class then
derive from that interface privately, whilst providing concrete
implementation of the methods exposed by the interface. The reason one
might want to implement a private inheritance is to force the user of
the concrete class to cast it to the interface without allowing them
to access the interface's methods through the concrete class itself.

I've not done enough C++ programming to say, and I don't have my
/Effective C++/ book on me, but my recollections on private inheritance
is designed for do not match your description. My recollection is that
private inheritance models an "is-implemented-in-terms-of" relationship,
which, following the concept of information hiding, should naturally be
private.

The idea have having pure interfaces that are implemented via private
inheritance sounds... hacky to me.
Car theCar;
IWindow* pCarWindow = reinterpret_cast<IWindow*>(&theCar);

I may be misremembering my C++, but this is an *extremely* dangerous
cast, one which would probably fail if you had multiple inheritance.
I am fully expecting some folk not to like the idea of private
inheritance in C++ and that is more than fair, but it works really
well especially when you really want to enforce the users of the
concrete class not to use the interfaces's methods directly from the
concrete class's instance.

The use of private inheritance is to hide implementation details--the
same reason you want to use private variables in general. Since you're
using reinterpret_cast instead of static_cast, you're explicitly
subverting the type system in this instance. I have no qualms about
using private inheritance, so long as it is used correctly.
So my question is how do I achieve the same in Java ? Any help of
suggestions would be truly appreciated.

As is suggested in /Effective Java/ (and in /Effective C++/ (more or
less) for that matter), "prefer composition to inheritance." The norm is
generally to have a private nested class, which may or may not be
static, depending on circumstances.
 
M

Mark Space

In C++ one can create an interface through a pure abstract class then
derive from that interface privately, whilst providing concrete
implementation of the methods exposed by the interface. The reason one


In Java I can think of two ways of doing this: add the "abstract"
keyword to a class, or declare the class package private so that it
isn't accessible to folks who might not use it correctly.

I think the latter is closer in spirit to what you want. Then you'd
compose your classes through has-a rather than inheritance. Depending
on exactly what you are doing, you might look at generics if you have a
large number of classes to make.

I'll leave the reinterpret_cast bit to the experts.
 
O

Owen Jacobson

Hi all,

Apologies if the subject has been already discussed but I have been
unable to find what I am looking for. My background is predominantly C+
+ and while I have been trying to familiarise myself with Java I have
come across something I can't get my head around.

In C++ one can create an interface through a pure abstract class then
derive from that interface privately, whilst providing concrete
implementation of the methods exposed by the interface. The reason one
might want to implement a private inheritance is to force the user of
the concrete class to cast it to the interface without allowing them
to access the interface's methods through the concrete class itself.

It might be informative to know *why* you'd want methods to be callable
via a superclass pointer but not via a subclass pointer. Given that in
any modern view of types a subtype exposes all of the operations of its
supertypes, that's a very odd thing to want.

Private inheritance doesn't get you that, though: public inheritance
with private overrides does. Consider:

$ cat inherit.cpp
#include <memory>
#include <iostream>

class Super {
public:
virtual ~Super () {};
virtual void foo () = 0;
};

class Sub : public Super {
private:
virtual void foo () {
std::cout << "Sub::foo()" << std::endl;
}
};

int main () {
// I don't want to manually clean this up.
std::auto_ptr<Super> super (new Sub ());
std::auto_ptr<Sub> sub (new Sub ());

super->foo ();
// Comment to suppress compile error.
sub->foo ();
}

$ g++ -std=c++98 -W -Wall -pedantic inherit.cpp -o inherit
inherit.cpp: In function ‘int main()’:
inherit.cpp:12: error: ‘virtual void Sub::foo()’ is private
inherit.cpp:24: error: within this context

I personally consider this a bad idea, but C++ allows it and it
achieves what you described wanting in a way that doesn't play fast and
loose with the language rules. Commenting out the sub->foo (); line
gives:

$ g++ -std=c++98 -W -Wall -pedantic inherit.cpp -o inherit
$ ./inherit
Sub::foo()
$

.... as expected.

(Note to any would-be C++ hacks tempted to copy this code: don't use
std::auto_ptr unless you understand the ownership model it uses in
detail. Use boost::shared_ptr instead, which is a simple
reference-counted pointer. I'm only using it here because ownership
details are irrelevant.)
Here is an example of how this works in C++:

class IWindow
{
public:
void openWindow( void ) = 0;
void closeWindow( void ) = 0;
}

IWindow::eek:penWindow is a redundant name ("Window" occurs twice); I'd
just use IWindow::eek:pen instead.
class Car: IWindow
{
private:
void openWindow( void ) {};
void closeWindow( void ) {};
}

Here, however, Car::eek:penWindow is appropriate. Conveniently, it
wouldn't conflict with or override IWindow::eek:pen. See below...
Car theCar;
IWindow* pCarWindow = reinterpret_cast<IWindow*>(&theCar);

I believe this risks undefined behaviour. comp.lang.c++ can probably
confirm or deny. Except for integer types, reinterpret_cast is never
what you want; with integer types it's only *rarely* what you want.
pCarWindow->openWindow();
pCarWindow->closeWindow();

I *know* this is undefined behaviour: pCarWindow is an IWindow*
pointing to something that is not an IWindow object. If it works on
your compiler, congrats, but never expect it to continue to work or to
work anywhere else. Virtual dispatch is not guaranteed by the language
for privately-inherited methods called from outside of the subclass.

You've misunderstood the point of private inheritance. In C++, private
inheritance is shorthand for composition, nothing more - an object of
class B, which privately extends class A, *is not* an A -- the fact
that there's a complete A object embedded in it is an implementation
detail. You can't use a B where an A is expected without relying on
compiler extensions or undefined behaviour.
So my question is how do I achieve the same in Java ? Any help of
suggestions would be truly appreciated.

By not exposing the implementation class. Consider:

public interface Window {
public void open ();
public void close ();
}

/* package visibility only */ class CarWindow {
public void open () { ... }
public void close () { ... }
}

Classes in the same package as CarWindow can create instances of it and
return them to callers as Window references. However, because Java uses
a strictly Liskov-compatible view of inheritance, someone with a
reference to a CarWindow can still call Window methods on it.

Cheers,
-o
 
O

Owen Jacobson

public interface Window {
public void open ();
public void close ();
}

/* package visibility only */ class CarWindow {

This was intended to be:
/* package visibility only */ class CarWindow implements Window {
public void open () { ... }
public void close () { ... }
}

Oops,
-o
 
S

sakis.panou

Hi all,


First of all thanks to everyone who took the time to have a look at
the post, much appreciated.

Owen's example as seen below is a much better implementation of what I
was suggesting it achieves
much more eloquently what I was try to describe. So big thanks to Owen
for setting me straight on
this one.
$ cat inherit.cpp
#include <memory>
#include <iostream>

class Super {
public:
        virtual ~Super () {};
        virtual void foo () = 0;

};

class Sub : public Super {
private:
        virtual void foo () {
                std::cout << "Sub::foo()" << std::endl;
        }      

};

int main () {
        // I don't want to manually clean this up.
        std::auto_ptr<Super> super (new Sub ());
        std::auto_ptr<Sub> sub (new Sub ());

        super->foo ();
        // Comment to suppress compile error.
        //sub->foo ();

}


Here why I think that above example has some serious mileage in it.
When programming to an interface
rather than implementation it is important to enforce that concept.

My interest as far as the design goes is purely on the contract formed
by the interface specification.
Whatever the internal mechanics of the concrete implementation of that
interface, are largely irrelevant.

I did purposely avoid mentioning anything about factories or lifetime
management of the interface
variable and by extension its concrete implementation.

I guess I view it as good practice to enforce the concept that the
type of the class that provides the
concrete implementation of the interface is not important, in fact I
want to ensure that by eliminating
the user from being able to access the interface implementation
methods through that type.

To borrow from the earlier example, I don't want the user to be able
to think in terms of the implementation:

Car theCar;
theCar.openWindow();

but in terms of the interface provide by that class:

IWindow* pWindow= &theCar;
pIWindow->openWindow();
By not exposing the implementation class. Consider:

public interface Window {
  public void open ();
  public void close ();

}

/* package visibility only */ class CarWindow implements Window {
public void open () { ... }
public void close () { ... }
}
}

Classes in the same package as CarWindow can create instances of it and
return them to callers as Window references. However, because Java uses
a strictly Liskov-compatible view ofinheritance, someone with a
reference to a CarWindow can still call Window methods on it.

This is a good example, however, it still allows someone with a
reference to CarWindow to
access the Window methods, as it was pointed out. Peter's example
above with the inner class
comes very close to what I would perceive as being a good solution as
it actually diminishes
the importance of the concrete implementation type. But it still
relies of exposing a public
method from the concrete class to get hold of the interface type.
Which of course there is nothing wrong with that,
but it wasn't quite what I was expecting, I guess it is just a
different way of viewing the same problem.

I appreciate that this second reply changes the context of the
question and I apologies for that ( also affectionately known as a bum
steer ;-) ) I am hoping you will bear with me on this.

To summarise when programming to an interface rather than
implementation I view it as a good practice to enforce that concept
through the type of the interface rather than that of the concrete
implementation, it certainly promotes high cohesion and low coupling.
Once more thanks to everyone who took the time to look at this post,
much appreciated.

Cheers,
Sakis
 
L

Lew

This is a good example, however, it still allows someone with a
reference to CarWindow to
access the Window methods, as it was pointed out. Peter's example
above with the inner class

Package-private classes also work.
comes very close to what I would perceive as being a good solution as
it actually diminishes
the importance of the concrete implementation type. But it still
relies of exposing a public
method from the concrete class to get hold of the interface type.
Which of course there is nothing wrong with that,
but it wasn't quite what I was expecting, I guess it is just a
different way of viewing the same problem.

It doesn't "expos[e] a public method from the concrete class". It exposes the
method from the interface.

If you are going to invoke a method, there must be a concrete type. There's
no way around that. The idioms shown to you all hide the concrete type and
expose only the interface to clients.

So your "second reply" doesn't change the context.
 
R

Roedy Green

In C++ one can create an interface through a pure abstract class then
derive from that interface privately, whilst providing concrete
implementation of the methods exposed by the interface. The reason one
might want to implement a private inheritance is to force the user of
the concrete class to cast it to the interface without allowing them
to access the interface's methods through the concrete class itself.

There are two fundamental rules you have to comply with:

1. all methods in an interface are public.

2. there are no private classes, though there are protected, and
package scope ones, as well as various flavours of nested classes.

Often you have both an interface and an abstract class. If you forgo
the interface you don't need to make all the methods public.

I don't see how you can do in Java what you have been doing. I think
in Java you have to do roughly what you want by hiding the details
inside a factory that produces only interface objects. The key may be
private constructors. There is a difference between preventing malice
and preventing error. Inside the program, you are more concerned with
error or unmaintainable code.

see http://mindprod.com/jgloss/factory.html
http://mindprod.com/jgloss/interface.html
http://mindprod.com/jgloss/abstract.html
http://mindprod.com/jgloss/interfacevsabstact.html
--
Roedy Green Canadian Mind Products
http://mindprod.com

"Learning is not compulsory... neither is survival."
~ Dr. W. (William) Edwards Deming (born: 1900-10-14 died: 1993-12-20 at age: 93))
 
L

Lew

Roedy said:
2. there are no private classes, though there are protected, and
package scope ones, as well as various flavours of nested classes.

More precisely, there are no private top-level classes. There aren't
any protected top-level classes either. Nested and inner classes can
have any access level: private, package-private, protected or public.
 
O

Owen Jacobson

Hi all,


First of all thanks to everyone who took the time to have a look at
the post, much appreciated.

Owen's example as seen below is a much better implementation of what I
was suggesting it achieves
much more eloquently what I was try to describe. So big thanks to Owen
for setting me straight on
this one.



Here why I think that above example has some serious mileage in it.
When programming to an interface
rather than implementation it is important to enforce that concept.

Absolutely, but that's a decision for the client to make, not the
provider. To borrow the List/ArrayList example Patricia's used: when
I'm writing code that needs a list, sometimes all I care about is
iterability, in which case I should use Iterable as it makes the fewest
demands of whatever provides that object. However, sometimes I really
do care about the extra promises ArrayList makes (eg., O(1) get(int) is
promised by ArrayList, but not by List). In that case, I can *and
should* accept only ArrayList.

Only the client code is in a position to decide which set of guarantees
and features it needs out of the public types in a given hierarchy.
Life's a little different for non-public types: those are often never
intended to be worked with directly by client code at all. When an
object of a non-public type escapes out to the program at large, it's
nearly always as a reference whose type is a more general interface or
parent type.
My interest as far as the design goes is purely on the contract formed
by the interface specification.
Whatever the internal mechanics of the concrete implementation of that
interface, are largely irrelevant.

If you have an interface with only one concrete implementation,
particularly in C++, you should consider collapsing the interface and
the implementing class. Retain the same guarantees (via documented pre-
and post-conditions and complexity guarantees, usually) that the
interface offered, rather than including the implementation guarantees,
to keep the freedom to bring back the interface in the future if you
eventually do need multiple implementations.

"Just in case" code has only one realistic response: "you aren't going
to need it."
I guess I view it as good practice to enforce the concept that the
type of the class that provides the
concrete implementation of the interface is not important, in fact I
want to ensure that by eliminating
the user from being able to access the interface implementation
methods through that type.

There's a fundamental truism in software development that states that
you can't save the user from themselves. This is true whether your user
is the end-user poking buttons in the UI or your user is another
programmer (or even yourself) calling your methods. You can only
protect your code from the user (by validating parameters and so on),
not the user from their code.
To borrow from the earlier example, I don't want the user to be able
to think in terms of the implementation:

Car theCar;
theCar.openWindow();

but in terms of the interface provide by that class:

IWindow* pWindow= &theCar;
pIWindow->openWindow();

Since it's theoretically possible to turn the former into the latter
completely automatically, I don't see that this gives you anything but
clutter in your code. The automatic promotion to IWindow will never
happen in C++ (too much code would break), but C++'s type promotion
rules could easily allow it.
This is a good example, however, it still allows someone with a
reference to CarWindow to
access the Window methods, as it was pointed out. Peter's example
above with the inner class
comes very close to what I would perceive as being a good solution as
it actually diminishes
the importance of the concrete implementation type. But it still
relies of exposing a public
method from the concrete class to get hold of the interface type.
Which of course there is nothing wrong with that,
but it wasn't quite what I was expecting, I guess it is just a
different way of viewing the same problem.

Fundamentally:

The Java equivalent of private inheritance is composition (has-a).

The Java equivalent of protected inheritance is protected composition (has-a).

The Java equivalent of public inheritance with private overrides is nil
- there isn't one. There are things you can do with similar semantics,
but there's no easy 1-1 translation.

Also? C++'s inheritance model is fundamentally *batshit insane*. Even
Haskell, which has very rich type relationships, doesn't have the same
degree of edge-caseyness.

Cheers,
-o
 
L

Lew

Peter said:
As members of the outer class, nested classes have access to all  
members of their outer classes.  

Pedantically speaking, only nested inner classes have that access.
Nested static classes do not.

The JLS reserves the term "inner class" for instance-level class
members. They use the term "member class" for both static nested
classes and inner classes, and more generally "member type" to
encompass member classes and member interfaces. Member interfaces are
always static, even without the keyword "static".

In my own parlance I usually speak of "nested class" to mean "static
member class" unless I need to emphasize that it's static.

<http://java.sun.com/docs/books/jls/third_edition/html/
classes.html#8.5>
Peter said:
So the interface implementation can simply call a private method
in the outer class if that makes more sense

With the proviso that the member class making the call must be an
inner class.
Non-static nested classes, known as "inner classes" require an

Yes, I repeated what you said. It was so that I could emphasize the
pedantic points.
instance of the outer class when being created, and have an implicit  
reference to that instance.  They can refer to instance members of the  
outer class in the same way any other member of the outer class could.

Since methods are members, this point applies to methods as well as
member variables and member types.
     -- In some situations, such as a name collision, you need to be  
specific about which type a member comes from.  In that case members of  
the outer class can be accessed via "<OuterClassName>.this.<member>",  
where "<OuterClassName>" and "<member>" are actually the names (without  
angle brackets) of the things those words describe.  For example, in my  
previous example, had the nested class been an inner class and been  
created with an instance of the outer class, you'd get at a member named  
"openWindow()" of "CarFactory" from within the "Car" class with  
"CarFactory.this.openWindow()".

Once again, your points already stated what I am saying, except I
wanted to draw out these details very overtly. Member types are among
the subtler parts of Java programming, and very powerful if correctly
used. Especially in the form of anonymous inner classes, they stand
in for what would be first-class functions in other languages. Swing
programming, for example, and other event-programming idioms in Java
rely heavily on nested classes, both static and inner. Member types
are an idiom well worth mastering.

Or excoriating, as the case may be.
 
R

Roedy Green

There aren't
any protected top-level classes either.

Its funny I never noticed that in all these years. I knew about
protected constructors.

--
Roedy Green Canadian Mind Products
http://mindprod.com

"Learning is not compulsory... neither is survival."
~ Dr. W. (William) Edwards Deming (born: 1900-10-14 died: 1993-12-20 at age: 93))
 
B

blue indigo

Pedantically speaking, only nested inner classes have that access.
Nested static classes do not.

Eh -- nested static classes do have access to even the private members of
the enclosing class. They have no implicit reference to an enclosing
instance, but they can invoke a private instance method of the enclosing
class on an explicit reference to an instance of it.

Ex:

public class Foo {
private int value;

public Foo (int value) {
this.value = value;
}

public static class FooComparator implements Comparator<Foo> {
public int compare (Foo a, Foo b) {
return (a.value < b.value)?-1:((a.value > b.value)?1:0);
}
}
}

which does not generate complaints about the accesses to a.value and
b.value in the compare() method. (Tested. NetBeans warns that I should
add @Override to the compare() method and accepts it. Sun's javac 1.6.0_10
accepts it without complaint. It needs to be put in a Foo.java with an
import of java.util.Comparator.)

The Java tutorial is somewhat misleading on this score, implying that
FooComparator should only be able to see public and default-access members
of Foo. The lexical scope suggests otherwise and the compiler concurs. The
Foo private instance variables are visible.

The distinction that needs to be clearer is that instances of the nested
class have no implicit "outer this" instance, and you can't just refer to
"value" unqualified within FooComparator but must (and may) use aFoo.value
to reference it.

So there's no enclosing instance to access, but the members of the
enclosing class are all visible.

Just a clarification.
 
M

Mike Schilling

Lew said:
Pedantically speaking, only nested inner classes have that access.
Nested static classes do not.

Sure they do. Try it. (And the outer call can access the inner one's
private parts too; I've never understood why that's a good idea.)
 
L

Lew

Sure they do.  Try it.  (And the outer call can access the inner one's
private parts too; I've never understood why that's a good idea.)

Yeah, blue indigo pointed out my error a couple of hours earlier. I
was thinking of direct access to instance members from a static
context, but as blue indigo mentioned, you just have to create an
instance of the outer class to mediate the access. It is just like
getting at instance variables from a static method that way.
 
M

Mike Schilling

Peter said:
I'll ditto the parenthetical comment. :) I understand why the
nested
class has access to the outer class (it's a member, and members have
access). But going the other way, it makes more sense to me that
"private means private", and unless you're a member of the nested
class (and the outer class isn't), you shouldn't be able to get at
it.

FWIW, C# gets this "right" (for certain definitions of "right" :) ).

Yes; that's what really started me thinking about the subject. There
are a few cases where C# rethought some of Java's decisions and
improved on them. This is one example; another is separating the
protected cloning method defined on Object from the public one defined
in the ICloneable interface.
 
L

Lew

Roedy said:
Its funny I never noticed that in all these years. I knew about
protected constructors.

I'm continually learning new things about Java that I had wrong. I was
corrected about one of them in this very thread.

Constructors can have any of the four access levels.
 
M

Mike Schilling

Lew said:
I'm continually learning new things about Java that I had wrong. I
was corrected about one of them in this very thread.

Constructors can have any of the four access levels.

I know someone who makes all constructors of abstract classes
protected, because they're always called from subclasses. I find this
anal, but can't find a good argument against it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,123
Latest member
Layne6498
Top