简体   繁体   中英

Is this a case of shadowed variables?

Totally new to programming. Got a hard-to-debug bug. Was trying to fix it for the last couple of days. Got myself to almost hysterical condition by doing that. Decided to sit down and just read the Java book on the random page to calm down. This page was about variable shadowing. Then suddenly I realized I had this nonsense in my code where I declare the same variables two times. I removed it and the bug seemed to vaporize.

public class Action extends JPanel { 
    private final Color BACKGROUND_COLOR = Color.BLACK; //JPanel background 
    private GameMemory memory = new GameMemory();        
    private int[][] grid = memory.getGrid(); 
    public static Color penColor = Color.GRAY;          //Variable for
                                                        //color

    public Action() { //Setting everything for JPanel
        memory = new GameMemory(); 
        grid = memory.getGrid(); 
        setBackground(BACKGROUND_COLOR); 
        setMinimumSize(new Dimension(360, 720)); 
        setPreferredSize(new Dimension(360, 720)); 
        setMaximumSize(new Dimension(360, 720)); 
        setVisible(true); 
        new Timer(100, new TimerListener()).start(); 
        //Setting Everything for keylistener
        this.setFocusable(true); 
        this.requestFocus();
        this.addKeyListener(new MyKeyListener());  
    }

So what do you guys think? Is this really the shadowing case?

There is no shadowing concept in your declarations.

Shadowing comes into picture ,when variables having same names with different scopes or Parent and Child have the same variables names and accessing them.

Possibilities are,

Shadowing a local variable Shadows An instance variable.

A instnace variable shadows the inherited variable from its parent.

   grid = memory.getGrid(); 

When you write this, the previous value overridden.

You can initialize a member variable many ways. You have initialized the variable twice. When it was declared, and in the constructor. There is no need to do it in both places. When you initialize a member variable at declaration, it will be initialized during every constructor call. The bug could have something to do with the order the variables are initialized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM