簡體   English   中英

Java:父方法訪問子類的靜態變量?

[英]Java: Parent Methods accessing Subclasses' static variables?

我試圖理解我圍繞Java多態性的方式。 我創建了一個父類,該類具有太多通用方法,所有子代將以相同的方式使用它們。
每個子類的子級都共享靜態信息,這些變量或信息將僅在父級中聲明的方法中使用。
希望實際上不可能從Parent方法訪問靜態變量的問題,
它是一種針對每個實例聲明公共信息的解決方案,但是由於將有數千個實例,因此浪費了內存。
我的意思的簡單闡述是以下代碼:

    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方法的全部意圖。



知道怎么做嗎?

一種選擇是通過抽象(非靜態)方法訪問子類的靜態數據:

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; }
}

當您創建新的testChild2()。print();時 testChield2上的靜態塊已執行,並將其值更改為2。

靜態塊在由ClassLoader加載時僅執行一次。

這給出您想要的輸出:

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

   class testChild2 extends testParent 
   {

    {
        testChild2.k =2;
    }
   }

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

    public static void main(String[] args)
    {

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

        new testChild1().print();
    }
 }

每次實例化該類時,都會執行非靜態代碼塊。

靜態變量特定於類本身。 如果要在類的不同實例中的同一字段具有不同的值,則該字段不能為靜態。

解決方案: 不要使k靜態。

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

class testChild2 extends testParent 
{
    {
        this.k =2;
    }
}

class testChild1 extends testParent{
    {
        this.k = 1;
    }

    public static void main(String[] args){
        new testChild1().print();
        new testChild2().print();
        new testChild1().print();
    }
}

演示
(忽略static class業務-只是使其在ideone中工作)。

過早的優化是萬惡之源。 我不認為您會遇到成千上萬個實例的內存問題,每個實例都有自己的數據,除非您在某種小型嵌入式系統上工作。 靜態變量無意於執行您要使用它們進行的操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM