Closed by Default
Although Cangjie fully supports object-orientation and class inheritance, it discourages abuse of inheritance, and in particular does not allow inheritance and overriding by default. Allowing inheritance by default encourages users to use a lot of inheritance and overriding. The mixture of overridden and non-overridden methods results in significant indirection in method definitions, which can make it hard to work out where a particular method is actually defined and what effect changes in base class definitions will have. Ill-thought-out inheritance hierarchies can also impose a rigid taxonomy which is hard to maintain and adapt as requirements and designs change.
For the sake of engineering friendliness, Cangjie adopts a closed-by-default design. That is, one cannot inherit from a class, nor override methods, by default. Developers need to explicitly decide whether their class should be allowed to have subclasses. This constraint reduces the abuse of inheritance.
Class Inheritance not Allowed by Default
In Cangjie, one cannot inherit from classes defined by developers by default. If the developer wants a class to have a subclass, they must explicitly use one of the open
, abstract
, or sealed
modifiers. (These modifiers have slightly different semantics from each other, but all enable inheritance from the modified class.)
class A {}
class B <: A {} // Error. **A** cannot be inherited.
open class C {}
class D <: C {} // OK
Member Method Overriding not Allowed by Default
In Cangjie, one cannot override member methods defined by developers by default. This means that even if a class has a subclass, the subclass cannot modify member methods of the parent class. If you want a member method to be overridable, you must explicitly use open
.
open class A {
func f() {}
open func g() {}
}
class B <: A {
override func f() {} // Error. **f** cannot be overridden.
override func g() {} // OK
}