0

I'm studying Swing in Java at first. above thing is correct and another thing is incorrect code.

Correct

public class Example extends JFrame{
    public Example() {
    }

Incorrect

public class Example extends JFrame{
    public Othor() {
    }

Despite it's not Constructor, why function name should be same with class name?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

1 Answers1

3

I am not sure what you mean with "Despite it's not Constructor" - in the first snippet, public Example() is a constructor, means it will be executed when the object is created with new Example(). In the second snippet, public Othor() would be a normal method of the class, even though it is missing the return type, so this does not compile (this is probably the error message you get, something like Return type is missing). The correct code for the second snipped would be something like

public class Example extends JFrame{
    public void othor() {
    }
}

(note that methods usually start with a non-capital letter). In this case, a default constructor would implicitly be created, but void othor() is a normal method of the class. Also note that this is just normal Java behaviour, and completely independant of Swing or any other toolkit or framework.

See also Purpose of a constructor in Java?

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123