Hacker News new | ask | show | jobs
by jdmichal 3625 days ago
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);
        }
    }