Sobes.tech
Middle

What method cannot be overridden in object-oriented programming?

sobes.tech AI

Answer from AI

In some languages, such as Ruby, the class method initialize, used for initializing new objects, cannot be directly called in a subclass as super.initialize to execute the parent class's logic. Instead, the subclass should explicitly call the super method within its own initialize implementation, which automatically invokes the parent class's initialize method.

In other languages, such as Java or C#, there are no "non-overridable" user-defined methods in the sense that any public or protected (!) method not marked as final (Java) or sealed (C#) can be overridden. However, constructors are considered a special type of "method" that cannot be overridden in the usual sense — you cannot declare a method with the same name and signature inside the subclass that replaces the parent constructor. The subclass can have its own constructors, which in turn call the parent class's constructors via super (Java) or : base (C#).

class Parent {
    Parent() {
        System.out.println("Parent constructor");
    }
    void method() {
        System.out.println("Parent method");
    }
}

class Child extends Parent {
    Child() {
        // Explicit call to the parent constructor is not needed,
        // if there are no parameters, it is called automatically.
        System.out.println("Child constructor");
    }
    @Override // Method overriding is possible
    void method() {
        System.out.println("Child method");
    }
}

Thus, generally speaking, constructors can be considered methods that cannot be overridden in the same sense as regular methods.

What method cannot be overridden in object-oriented… - sobes.tech