繁体   English   中英

主要对象的方法

[英]methods of objects within main

是否可以在类中的方法中实例化一个对象,然后在main中使用实例化对象的方法之一? 我可以修复以下代码吗?

    public class Test {

    public void Testmethod()  {

        someclass a = new someclass();

    }

    public static void main(String[] args) {

        a.methodfromsomeclass(); 

    }

}

您需要解决三个问题:

1)您已经在Testmethod声明a局部变量。 这意味着只能在Testmethod访问它。 如果您希望一个变量即使在Testmethod执行完成后仍然可以使用,则应将其Testmethod Test的实例变量。 这意味着Test的实例将包含变量,并且Test实例方法( Testmethod除外)将能够访问它。

声明实例变量看起来像这样:

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 你需要确保你叫Testmethod您尝试使用前a (它不会仅仅因为它出现在代码中而被自动调用。您必须编写调用它的代码。)

另外,请遵守正确的命名约定:类以大写字母( SomeClass )开头,方法以小写字母( testMethod )开头,如果名称包含多个单词,则第二个单词和后面的单词以大写字母开头字母。

暂无
暂无

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

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