In C++ we can extend (derive) a base class privately to a child class:
class Base
{
// ....
};
class Child : private Base
{
// ....
};
What is Java's corresponding syntax ? If Java hasn't it, what do Java programmers?
Java's syntax for inheritance:
class Base {}
class Child extends Base
{
// ...
}
There is no private inheritance in Java. 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.
In most cases, you can use composition to do the same thing.
public class Child{
private Base base;
public Child(...){
base = new Base(...);
}
}
To a certain extent, you could use a private inner class to achieve a similar effect:
public class Base {
private int privateMember = 10;
private class Child extends Base {
public Child() {
System.out.println("I can see your privates: " + privateMember);
}
}
public static void main(String[] args) throws Exception {
Base t = new Base();
Child c = t.new Child();
}
}
When running the above code, the following message gets printed on the console:
I can see your privates: 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With