Hacker News new | ask | show | jobs
by tigershark 3625 days ago
You wrote this: "Inheritance is nothing but composition with some default implicit virtual method routing." In response to my post where I said that inheritance and composition are two different tools and doesn't make sense to say that one is always better than the other. So it seems to me that you think that inheritance and composition are the same concepts given your words that I quoted and given that you were arguing with my definition of different tools.

Edit: I don't see any composition in your example, just an interface implementation.

1 comments

OK, I should have stated that inheritance is a bundling of multiple tools, composition and default implicit virtual method routing being two of them. It also creates an is a relationship, which in my version of an inheritance-less world would be handled explicitly via interfaces, which I included in my original "toolbox".

EDIT: Notice how I can enforce the invariants of `Square`, while composing a `Rectangle` and implementing `IRectangle`. This works because composition allows me to encapsulate the problematic setter methods of `Rectangle`, which is not something I can do if I inherit it.

    class Square implements IRectangle {
        private final Rectangle rectangle;

        public Square(final double size) {
            this.rectangle = new Rectangle(size, size);
        }

        public double getWidth() {
            return this.rectangle.getWidth();
        }

        public double getHeight() {
            return this.rectangle.getHeight();
        }

        public double getSize() {
            return this.rectangle.getWidth();
        }

        public double setSize(final double size) {
            this.rectangle.setWidth(size);
            this.rectangle.setHeight(size);
        }
    }