简体   繁体   English

这是阴影变量的情况吗?

[英]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. 决定坐下来,只是在随机页面上阅读Java书籍以使自己平静下来。 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. 一个instnace变量屏蔽从其父继承的变量。

   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. 该错误可能与变量初始化的顺序有关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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