【问题标题】:How to use father's method with son's variable in java?java - 如何在java中使用父亲的方法和儿子的变量?
【发布时间】:2013-11-19 12:55:03
【问题描述】:

由于我的代码内容很长,我会尽量保持抽象。 所以,我有一个抽象的父亲,包含适用于所有儿子的方法。

abstract class a {
 protected final void a_method() {
  ...do stuff
 }
}

我还有另外两个扩展了 a 的类

class b extends a {
  static int _int = 3;
}

还有,

class c extends a {
  static int _int = 2;
}

如你所见,我所有的 b 总是有相同的静态 _int 变量,我所有的 c 也总是有相同的 _int 变量。 a_method() 方法对于两个儿子来说是完全相同的代码,只是使用了儿子的变量。 我可以避免代码重复吗? 由于我的变量是静态的,所以我不能在a 中声明它,因为每个儿子的班级需要不同(每个扩展班级的内容不同)

【问题讨论】:

  • parentchild 听起来更好:)
  • 你试过Class bthis._int = 3;
  • 需要是静态的吗?
  • @user2860598 如果您在 a 类中声明它并按照您的建议使用 this 在任何一个子类中对其进行更改,那么更改将反映在所有其他子类中。跨度>
  • @Chris 是的,否则会更容易,因为我可以在父项中声明它并在子项中覆盖

标签: java oop inheritance abstract-class


【解决方案1】:

更简单的方法是使用类 A 中的抽象方法返回子类 int 值。

abstract class a {
    protected final void a_method() {
       int i = getValue();

       ...do stuff
    }

    protected abstract int getValue();

}

在你的子类之后

class b extends a {
    static int _int = 3;

    protected int getValue() {
       return _int;
    }
}

【讨论】:

    【解决方案2】:

    我在这种情况下使用的解决方案是 a、b 和 c 都实现一个声明 int getTheVariable() 的接口。这个方法在a中是抽象的。

    然后在a 中使用getTheVariable()。返回值由具体实现决定。

    interface Foo {
         int getTheVariable();
    }
    
    abstract class A implements Foo {
        abstract int getTheVariable();
        int doSomeWork() {
            return 5 * getTheVariable();
            }
        }
    
    class B extends A implements Foo {
        int getTheVariable() { return 3; }
        }
    
    class C extends A implements Foo {
        int getTheVariable() { return 2; }
        }
    

    我没有尝试编译它,它应该很接近。

    现在“父”类 A 可以提供主代码,但可以根据需要使用 B 和 C 中的值。这些类中的值可以是静态的。

    【讨论】:

    • 谢谢。这似乎很简单。我认为也许有一些更隐含的方式来获得它。我猜虚拟方法也可以
    【解决方案3】:

    静态意味着变量属于一个类而不是单个实例。由于您的要求是静态变量在两个类中具有不同的值,因此您的问题不会被视为代码重复。

    如果它不是静态的,你可以在一个类中定义变量,然后在 b 类和 C 类构造函数中初始化它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-04
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 2013-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多