什么是脆弱的基类问题?

java中脆弱的基类问题是什么?

脆弱的基类是inheritance的常见问题,它适用于Java和支持inheritance的任何其他语言。

简而言之,基类是您inheritance的类,它通常称为脆弱类,因为对此类的更改可能会在从其inheritance的类中产生意外结果。

减轻这种情况的方法很少; 但是在使用inheritance时没有直接的方法可以完全避免它。 您可以通过在Java中将类声明标记为final来阻止从类inheritance的其他类。

避免这些问题中最严重的最佳做法是将所有类标记为final,除非您特意打算从它们inheritance。 对于那些打算inheritance的人来说,就像设计一个API一样设计它们:隐藏所有的实现细节; 严格对待你所发出的内容并注意你所接受的内容,并详细记录该课程的预期行为。

当对其进行的更改破坏派生类时,基类称为fragile。

 class Base{ protected int x; protected void m(){ x++; } protected void n(){ x++; // <- defect m(); } } class Sub extends Base{ protected void m(){ n(); } } 

所有“Colin Pickard”所说的都是真的,在这里我想添加列出在编写可能导致Java语言中的这类问题的代码时受到保护的最佳实践…

  1. 让所有类成为最终类,因为您不希望它们被inheritance
  2. 如果你不能并且你必须使用inheritance(例如抽象类),那么使其所有已实现的方法最终不被其子类修改(即使受保护的方法通常也是一个坏主意,subClasses应该不太了解它的子类)…
  3. 尽量不要使用relationShip [is a]而是尝试使用[使用]关系表之间的关系图使用接口来避免扩展问题。
  4. 每个扩展都可以用implements替换,如果你必须在这里创建一个默认的实现,那么代码spinet:
 public interface MyBehavior { void doAction(); static class Implementation implements MyBehavior { public void doAction() { //do some stuff } } } // instead of doing extends To a class that have the doAction method // we will make a [use a] relationShip between the Example class & the Implementation class public class Example { private MyBehavior.Implementation helper = new MyBehavior.Implementation(); public void doAction() { this.helper.doAction(); } }