简体   繁体   English

主要对象的方法

[英]methods of objects within main

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? 是否可以在类中的方法中实例化一个对象,然后在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 . 1)您已经在Testmethod声明a局部变量。 This means it can be accessed only inside Testmethod . 这意味着只能在Testmethod访问它。 If you want a variable that will live even after Testmethod is done executing, you should make it an instance variable of Test . 如果您希望一个变量即使在Testmethod执行完成后仍然可以使用,则应将其Testmethod 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. 这意味着Test的实例将包含变量,并且Test实例方法( Testmethod除外)将能够访问它。

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. 2) main将无法访问实例变量,因为main是静态的。 You can't make main non-static, either; 您也不能使main非静态; Java requires it to be static. Java要求它是静态的。 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: 您应该做的是编写一个实例方法(例如,称为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) The way you've written it so far, a new someclass would never be constructed, since you never call Testmethod . 3)到目前为止,您从未编写过新的someclass ,因为您从未调用Testmethod You'll need to make sure you call Testmethod before you try to use a . 你需要确保你叫Testmethod您尝试使用前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. 另外,请遵守正确的命名约定:类以大写字母( SomeClass )开头,方法以小写字母( testMethod )开头,如果名称包含多个单词,则第二个单词和后面的单词以大写字母开头字母。

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

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