Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fragile base class problem?

Tags:

java

oop

What is the fragile base class problem in java?

like image 342
SunilRai86 Avatar asked May 27 '10 13:05

SunilRai86


People also ask

What classes Cannot be base class?

A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster.

What is base class example?

A class derived from a base class inherits both data and behavior. For example, "vehicle" can be a base class from which "car" and "bus" are derived. Cars and buses are both vehicles, but each represents its own specialization of the vehicle base class.

What is base class in inheritance?

The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class.


3 Answers

A fragile base class is a common problem with inheritance, which applies to Java and any other language which supports inheritance.

In a nutshell, the base class is the class you are inheriting from, and it is often called fragile because changes to this class can have unexpected results in the classes that inherit from it.

There are few methods of mitigating this; but no straightforward method to entirely avoid it while still using inheritance. You can prevent other classes inheriting from a class by labelling the class declaration as final in Java.

A best practice to avoid the worst of these problems is to label all classes as final unless you are specifically intending to inherit from them. For those to intend to inherit from, design them as if you were designing an API: hide all the implementation details; be strict about what you emit and careful about what you accept, and document the expected behaviour of the class in detail.

like image 80
Colin Pickard Avatar answered Sep 21 '22 12:09

Colin Pickard


A base class is called fragile when changes made to it break a derived class.

class Base{     protected int x;     protected void m(){        x++;     }      protected void n(){       x++;      // <- defect        m();      }  }   class Sub extends Base{         protected void m(){             n();         }     } 
like image 21
stacker Avatar answered Sep 19 '22 12:09

stacker


It is widely described in below article By Allen Holub on JavaWorld

Why extends is evil. Improve your code by replacing concrete base classes with interfaces

like image 26
bastiat Avatar answered Sep 21 '22 12:09

bastiat