是否可以在类中的方法中实例化一个对象,然后在 main 中使用实例化对象的方法之一?我可以修复以下代码吗?
public class Test {
public void Testmethod() {
someclass a = new someclass();
}
public static void main(String[] args) {
a.methodfromsomeclass();
}
}
最佳答案
您需要解决三个问题:
1) 您已将 a
声明为 Testmethod
内的本地变量。这意味着它只能在 Testmethod
内部访问。如果您希望一个变量即使在 Testmethod
执行完成后仍然存在,您应该将其设为 Test
的实例变量。这意味着 Test
的实例将包含该变量,并且除 Testmethod
之外的 Test
的实例方法将能够访问它。
声明实例变量看起来像这样:
public class Test {
private someclass a; // please choose a better variable name
//...... other code ..........//
}
2) main
将无法访问实例变量,因为 main
是静态的。您也不能将 main
设置为非静态; Java要求它是静态的。您应该做的是编写一个实例方法(例如,称为doMainStuff
,或一些更好的名称),并让您的main
创建一个新的Test
对象,例如:
public void doMainStuff() {
// something that calls Testmethod
a.methodfromsomeclass(); // use a better name than "a"
// other code
}
public static void main(String[] args) {
new Test().doMainStuff();
}
3) 到目前为止,您编写的方式永远不会构造新的someclass
,因为您从未调用Testmethod
。您需要确保在尝试使用 a
之前调用 Testmethod
。 (它不会仅仅因为它出现在代码中而自动被调用。您必须编写调用它的代码。)
此外,请遵守正确的命名约定:类以大写字母开头 (SomeClass
),方法以小写字母开头 (testMethod
),并且如果名称有多个单词,则第二个及后面的单词以大写字母开头。
关于java - main 中对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34553114/