Is it possible to instantiate an object in a method within a class and then use one of the methods of the instantiated objects within main? Can I fix the following code?
public class Test {
public void Testmethod() {
someclass a = new someclass();
}
public static void main(String[] args) {
a.methodfromsomeclass();
}
}
There are three problems you need to fix:
1) You've declared a
to be a local variable inside Testmethod
. This means it can be accessed only inside Testmethod
. If you want a variable that will live even after Testmethod
is done executing, you should make it an instance variable of Test
. That means that an instance of Test
will contain the variable, and instance methods of Test
, other than Testmethod
will be able to access it.
Declaring an instance variable looks something like this:
public class Test {
private someclass a; // please choose a better variable name
//...... other code ..........//
}
2) main
won't be able to access the instance variable, because main
is static. You can't make main
non-static, either; Java requires it to be static. What you should do is write an instance method (called doMainStuff
, for example, or some better name), and have your main
create a new Test
object, something like:
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) The way you've written it so far, a new someclass
would never be constructed, since you never call Testmethod
. You'll need to make sure you call Testmethod
before you try to use a
. (It doesn't automatically get called just because it appears in the code. You have to write code that calls it.)
Also, please obey proper naming conventions: classes begin with an upper-case letter ( SomeClass
), methods begin with a lower-case letter ( testMethod
), and if a name has multiple words, the second and later words begin with upper-case letters.
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.