Java:父方法访问子类的静态变量? [英] Java: Parent Methods accessing Subclasses' static variables?

查看:133
本文介绍了Java:父方法访问子类的静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解我在Java中处理多态性的方式.我创建了一个父类,该类具有太多通用方法,所有子代都将以相同的方式使用它们.
每个子类的子级都共享静态信息,这些变量或信息将仅在父级中声明的方法中使用.
希望实际上无法从Parent方法访问静态变量的问题,
这是一种针对每个实例声明公共信息的解决方案,但是由于将有1000个实例,因此浪费了内存.
我的意思的简单阐述是以下代码:

I am trying to understand my way around polymorphism in Java. I created a parent class that has too many common methods that all children will use in the same manner.
Each of the subclasses' children all share static information, These variables or information will be used in the methods declared only in the parent.
The problem wish accessing static variables from Parent methods seems not really possible,
Its a solution to declare the common information per instance but since there will be 1000s of instances its such a waste of memory.
A simple elaboration of what i mean is the following code :

    class testParent {
    static int k;
    public void print()
    {
      System.out.println(k);    
    }
   }

   class testChild2 extends testParent 
   {

    static
    {
        testChild2.k =2;
    }
   }

   public class testChild1 extends testParent{
    static
    {
        testChild1.k = 1;
    }

    public static void main(String[] args)
    {

        new testChild1().print();
        new testChild2().print();

        new testChild1().print();
    }
 }

我期望的输出是
1
2
1.
但是发生的是:
1
2
2
可能有人认为,在每个子类的初始化时,都会设置该子类的静态变量,然后所有引用该子类的方法都可以访问相应的"k"值.
但是实际上发生的是,所有子类都在所有子类都共享的同一静态变量中进行编辑,因此破坏了我为每个子类及其实例使用静态变量并在Parent访问这些变量时使用commmon方法的全部意图.

the output i expect was
1
2
1.
but what happens is :
1
2
2
One might think that on the initiation of each subclass the static variables of this subclass is set and then all methods referring to this subclass has access to the corresponding 'k' value.
But what actually happens is that all subclasses edit in the same static variable that is shared along all subclasses and hence destroys my whole point of using static variables for each subclass and its instances and using commmon methods in the Parent accessing these variables.



知道如何做到这一点吗?



Any idea how can this be done ?

推荐答案

一种选择是通过抽象(非静态)方法访问子类的静态数据:

An option is to access the subclasses' static data through an abstract (non-static) method:

abstract public class Parent {
   protected abstract int getK();

   public void print() {
      System.out.println(getK());
   }
} 

public class Child1 extends Parent {
   private static final int CHILD1_K = 1;

   protected int getK() { return CHILD1_K; }
}

public class Child2 extends Parent {
   private static final int CHILD2_K = 2;

   protected int getK() { return CHILD2_K; }
}

这篇关于Java:父方法访问子类的静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆