Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private extend in Java

Tags:

java

c++

oop

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?

like image 935
masoud Avatar asked Feb 22 '23 08:02

masoud


2 Answers

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(...);
   }
}
like image 60
ApprenticeHacker Avatar answered Feb 27 '23 04:02

ApprenticeHacker


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
like image 23
Óscar López Avatar answered Feb 27 '23 04:02

Óscar López