Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 定义超类中私有子类成员的相同处理_Java_Inheritance_Private_Abstract - Fatal编程技术网

Java 定义超类中私有子类成员的相同处理

Java 定义超类中私有子类成员的相同处理,java,inheritance,private,abstract,Java,Inheritance,Private,Abstract,我有一个家长班: abstract class Parent { abstract int getX(); } 以及两种不同的子类实现: class AgnosticChild extends Parent { private int x = 5; @Override int getX() { return x; } } class ManipulativeChild extends Parent { private static int x = 5;

我有一个家长班:

abstract class Parent {
  abstract int getX();
}
以及两种不同的子类实现:

class AgnosticChild extends Parent {

  private int x = 5;

  @Override
  int getX() {
    return x;
  }
}

class ManipulativeChild extends Parent {

  private static int x = 5;

  ManipulativeChild() {
    x++;
  }

  @Override
  int getX() {
    return x;
  }
}

两种
getX()
实现都是相同的。有没有办法在保留
x
的不同实现的同时消除这种冗余?假设
getX()
实现在实践中要复杂得多。

您可以将int变量拉到父类,并在那里实现
getX
方法

abstract class Parent {
    private int x;

    public Parent(int x) {
        this.x = x;
    }

    public int getX() {
        return x;
    }

}

class AgnosticChild extends Parent {

    public AgnosticChild() {
        super(5);
    }


}

class ManipulativeChild extends Parent {


    ManipulativeChild() {
        super(6);
    }
}

更新:如果您想将
manipivechild
中的
x
声明为非静态字段,则上面的代码片段仅等于您的代码。否则,这是两个不同的实现,无法按照建议的方式进行重构。

您可以将int变量拉到父类,并在那里实现
getX
方法

abstract class Parent {
    private int x;

    public Parent(int x) {
        this.x = x;
    }

    public int getX() {
        return x;
    }

}

class AgnosticChild extends Parent {

    public AgnosticChild() {
        super(5);
    }


}

class ManipulativeChild extends Parent {


    ManipulativeChild() {
        super(6);
    }
}

更新:如果您想将
manipivechild
中的
x
声明为非静态字段,则上面的代码片段仅等于您的代码。否则,这是两个不同的实现,无法按照建议的方式进行重构。

不,这两个实现并不相同——一个访问静态字段,另一个访问实例字段。因此,尽管它们看起来一模一样,但在功能上却大不相同;在不改变类的行为的情况下,这里没有重用的机会。

不,这两个实现是不同的——一个访问静态字段,另一个访问实例字段。因此,尽管它们看起来一模一样,但在功能上却大不相同;根据OP的代码,x在
AgnosticChild
中是静态的,但在
manufactivechild
-->中不是静态的,它不能是相同的
x
,感谢您的更正。根据OP的代码,我在回答中添加了限制,x在
不可知儿童
中是静态的,但在
操纵儿童
-->中不是静态的,它不能是相同的
x
,感谢您的更正。我在回答中增加了限制