本文介绍了爪哇|父类和子类中的静态变量 |从父类访问子 var 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下,我有一些具有独特静态变量的子类,称为x".所有这些子类都以相同的方式使用静态 var,所以我想减少代码重复并将功能放在超类中.在这种情况下,超类中的方法getX".从这里我想返回 x 的值.现在我面临的问题是它使用超类的 x 值而不是子类的值.如何从超类访问子类的 x 值?

i have a few sub classes with unique static vars in this case called 'x'.All of those sub classes are using the static var the same way, so I want to reduce code duplication and put the functionality in the super class.In this case the method 'getX' in the super class. From here I want to return the value of x. Right now I'm facing the issue that it uses the x value of the super class and not the value of the child class. How can I access the x value of the sub class from the super class?

public class Playground {

  public static void main(String[] args) {
    Parent parent = new Parent();
    Child child = new Child();
    Child1 child1 = new Child1();

    System.out.println("Parent.x " + parent.x);
    System.out.println("child.x " + child.x);
    System.out.println("child.x " + child1.x);

    System.out.println("get x: " + parent.getX());
    System.out.println("get x: " + child.getX());
  }
}

class Parent {
  static String x = "static of parent";
  String y = "instance of parent";

  String getX() {
      return x;
  }
}

class Child extends Parent {
  static String x = "static of child";
  String y = "instance of child";
}

class Child1 extends Parent {
  static String x = "static of child1";
  String y = "instance of child";
}

此代码打印出来:Parent.x 静态父child.x 孩子的静态child1 的 child.x 静态得到 x:父母的静态get x: static of parent <-- 这里应该是static of child

希望有人能帮助我.

干杯

推荐答案

解决方案可能是在 Parent 中没有静态字段,而是在实例字段中.

A solution could be to not have a static in the Parent, but an instance field.

class Parent{
    private final X x
    public Parent(X x){
        this.x = x;
    }

    public X getX() {
        return x;
    }
}

然后在你的孩子中,你仍然可以有一个静态的,但你在构造函数中传递它

Then in your child, you still can have a static, but you pass it at the constructor

class Child extends Parent {
    static final X x = ....
    public Child() {
        super(x);
    }
}

这篇关于爪哇|父类和子类中的静态变量 |从父类访问子 var 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 19:43