0

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"

And of course using advise in error, gives this error:

"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. Anyone could explain how to do it properly in Java?

Deepak Bhatia
  • 6,230
  • 2
  • 24
  • 58
Andrius
  • 19,658
  • 37
  • 143
  • 243

4 Answers4

7

Your constructor is wrong (you forgot the brackets).

It has to be

public A() {

}
Maroun
  • 94,125
  • 30
  • 188
  • 241
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
0

You are getting this error because you have not wrote the constructor correctly. It should be:

public A() {
    my_method();
}
0

constructor is missing (). use

public A() { }

codingenious
  • 8,385
  • 12
  • 60
  • 90
0

Just to expand on Jeroen's answer as it seems you are quite new to Java:

Your private method can be called from inside another method in your class. E.g.

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 e.g. 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.

So your mistake was that in your constructor you had not put () after the method name (A in this case).

shmish111
  • 3,697
  • 5
  • 30
  • 52