简体   繁体   English

Java 在子类中设置变量

[英]Java setting variables in subclasses

I have a Java project (let's call it Project A) that consists of a class and its subclass.我有一个 Java 项目(我们称之为项目 A),它由一个类及其子类组成。 I packaged this project into a .jar file, which I included as a Maven dependency in another project (let's call it Project B).我将这个项目打包成一个 .jar 文件,我将其作为 Maven 依赖项包含在另一个项目中(我们称之为项目 B)。

My subclass in Project A contained a variable as such:我在项目 A 中的子类包含一个变量,如下所示:

int foo = null;

And I wanted to perform the following in Project B:我想在项目 B 中执行以下操作:

Subclass.foo = 3;

However, Java kept throwing me a java.lang.ExceptionInInitializerError whenever I tried to do this, which it said was caused by a null pointer error.但是,每当我尝试这样做时,Java 都会向我抛出 java.lang.ExceptionInInitializerError,它说这是由空指针错误引起的。

The minute I moved this variable to the base class in Project A though, it worked.我将这个变量移动到项目 A 中的基类的那一刻,它起作用了。 I was able to set the value of foo in Project B.我能够在项目 B 中设置 foo 的值。

I have no idea why this worked, would someone who knows about Java be willing to explain this to me?我不知道这为什么有效,了解 Java 的人愿意向我解释这一点吗?

That's because there is no static variable foo on Subclass .那是因为Subclass上没有静态变量foo You can only use static variables with the class name like this.您只能像这样使用具有类名的静态变量。 To use non-static variables, you have to instantiate the class with the new keyword.要使用非静态变量,您必须使用new关键字实例化该类。

Try one of the following:尝试以下方法之一:

Option #1:选项1:

Class 1:第一类:

public static int foo = null;

Class 2:第 2 类:

Subclass foo = 3;

Option #2:选项#2:

Class 1:第一类:

public int foo = null;

Class 2:第 2 类:

Subclass subclass = new Subclass();
subclass.foo = 3;

Also, note that I added the public modifier.另外,请注意我添加了public修饰符。 By default, the variable is only available to others in the same package.默认情况下,该变量仅对同一包中的其他人可用。 Given you have two different projects, I don't think that's the case here.鉴于您有两个不同的项目,我认为这里不是这种情况。


Edit:编辑:

Someone ( Lino ) reminded me in the comments that int can't be null .有人( Lino )在评论中提醒我 int 不能为null Either replace int with Integer , or null with 0 .要么用Integer替换int ,要么用0替换null

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

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