简体   繁体   English

Java-如何在定义的类中加载方法?

[英]Java - how to load method inside class it is defined?

For example I have this code: 例如,我有以下代码:

public class A
{
    private void my_method(){
        //do something
    }
}

So how can I call that method for code below to use it? 那么如何在下面的代码中调用该方法来使用它呢? I saw in one example it was done like this: 我在一个示例中看到它是这样完成的:

public class A
{
    public A {
        my_method();
    }

    //some other code

    private void my_method(){
        //do something
    }
}

But trying this gives me this error: 但是尝试这样做会给我这个错误:

"Syntax error on token "public", class expected after this token" “令牌“ public”上的语法错误,此令牌后应为类”

And of course using advise in error, gives this error: 当然,错误地使用advisor会出现此错误:

"The nested type A cannot hide an enclosing type" So it seems that code I saw is bad or somehow I'm doing something wrong. “嵌套的类型A无法隐藏封闭的类型”,所以看来我看到的代码很糟糕,或者我做错了什么。 Anyone could explain how to do it properly in Java? 任何人都可以解释如何在Java中正确地做到这一点?

Your constructor is wrong (you forgot the brackets). 您的构造函数是错误的(您忘记了括号)。

It has to be 它一定要是

public A() {

}

You are getting this error because you have not wrote the constructor correctly. 因为没有正确编写构造函数,所以出现此错误。 It should be: 它应该是:

public A() {
    my_method();
}

constructor is missing (). 构造函数丢失()。 use 采用

public A() { }

Just to expand on Jeroen's answer as it seems you are quite new to Java: 只是为了扩展Jeroen的答案,因为您似乎对Java相当陌生:

Your private method can be called from inside another method in your class. 可以从类中的另一个方法内部调用您的私有方法。 Eg 例如

public class A
{
    public void anotherMethod() {
        my_method();
    }

    private void my_method(){
        //do something
    }
}

The code you provided was called within the constructor of the class. 您提供的代码在类的构造函数中调用。 This is a special method which is called when an object of type A is constructed eg new A(); 这是一种特殊的方法,当构造类型为A的对象(例如new A();时会调用该方法new A(); . You can tell it's a constructor because it has no return type specified: 您可以说它是一个构造函数,因为它没有指定返回类型:

public A() {
}

rather than a normal method: 而不是常规方法:

public void a() {
}

Something to note there is that in Java it is convention (but not strictly required) to name normal methods with a lowercase first letter and classes/objects/constructors with an upper case first letter. 需要注意的是,在Java中,习惯上(但并非强制要求)以小写首字母命名普通方法,并以大写首字母命名类/对象/构造函数。

So your mistake was that in your constructor you had not put () after the method name ( A in this case). 因此,您的错误是在构造函数中,您没有将()放在方法名称之后(在本例中为A )。

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

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