简体   繁体   English

如何读写抽象类的变量

[英]How to read and write to variables of an abstract class

Put simply, I have an abstract class containing several variables and methods. 简而言之,我有一个包含几个变量和方法的抽象类。 Other classes extend this abstract class, yet when I try to read the private variable in the abstract class by calling getter methods inside the abstract class, it returns null as the value of the variable. 其他类扩展了该抽象类,但是当我尝试通过调用抽象类内部的getter方法读取抽象类中的私有变量时,它将返回null作为变量的值。

public class JavaApplication {

    public static void main(String[] args) {
        NewClass1 n1 = new NewClass1();
        NewClass2 n2 = new NewClass2();

        n1.setVar("hello");
        n2.print();

    }
}



public class NewClass1 {

    public String firstWord;

    public void setVar(String var) {
        firstWord = var;
    }

    public String getVar () {
        return firstWord;
    }

}



public class NewClass2 extends NewClass1{

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

    public String makeCall() {
        return getVar();
    }

}

Still prints out null. 仍然打印为空。

Until the String is initialized, it will be null. 在初始化String之前,它将为null。 You should probably have a constructor in the abstract class to set it. 您可能应该在抽象类中有一个构造函数来进行设置。

public abstract class Command
{
     String firstWord; // = null 

     protected Command(){}

     protected Command( String w )
     {
         firstWord = w;
     }
     //...
}

public class Open extends Command
{
     public Open()
     {
         this( "your text" );
     }

     public Open( String w )
     {
         super( w );
     }

     // ...
}

If you need to modify the firstWord string everytime execute() is called then it may not be necessary to use a constructor with a String parameter (I added a default constructor above). 如果每次execute()都需要修改firstWord字符串,则可能没有必要使用带有String参数的构造函数(我在上面添加了默认构造函数)。 However, if you do it this way then either 但是,如果您这样做,

  • You must make sure setFirstWord() is called before getFirstWord() , or, 必须确保在getFirstWord()之前调用setFirstWord() getFirstWord() ,或者,
  • Handle the case when getFirstWord() returns null . 处理getFirstWord()返回null This could be by simply using a default value (maybe determined by each subclass) or something else, like failing to execute. 这可以通过简单地使用默认值(可能由每个子类确定)或其他类似的方法来执行,例如执行失败。

As I do not know all the details of your implementation I cannot tell you further information. 由于我不知道您实施的所有细节,因此无法告诉您更多信息。

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

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