[Java] 생성자 리턴값

wafe의 이미지

public class ConTest {
        public ConTest() {
                System.out.println("jie");
        }

        public int ConTest() {
                System.out.println("ff");
                return 1;
        }

        public static void main(String[] args) {
                ConTest ct = new ConTest();
        }
}

이 코드가 제대로 컴파일되고 실행되는 이유는 뭘까요? 생성자에 리턴값이 있으면 컴파일 에러가 나는게 정상아닌가요?

nohmad의 이미지

        public static void main(String[] args) {
                ConTest ct = new ConTest();
                System.out.println(ct.ConTest());
        }

한 줄을 추가해보니 알겠군요. 자바라고 언제나 깔끔한 코드만 나오는 것은 아니라는....-_-;

iolo의 이미지

nohmad wrote:
        public static void main(String[] args) {
                ConTest ct = new ConTest();
                System.out.println(ct.ConTest());
        }

한 줄을 추가해보니 알겠군요. 자바라고 언제나 깔끔한 코드만 나오는 것은 아니라는....-_-;

        public static void main(String[] args) {
                System.out.println(new ConTest().ConTest());
        }

해도 됩니다.

그리고 자바에선 리턴타입도 메소드 이름에 포함되는 요소죠. VM스펙을 보시면 나올겁니다. 근데, 솔직히 저도 저런 메소드 이름이 되리라곤 생각도 안해봤네요.

----
the smile has left your eyes...

atie의 이미지

Method Name은 class name을 제외한 어떠한 이름으로 해도 된다고 했는데... class name을 써도 된다는 말이 되네요.(저도 이렇게 명명한 적은 없었던 것 같군요.) javac로 하더라도 아무 에러가 안뜨는군요. 이클립스에서는 생성자와 이름이 같다는 warning은 보여주는군요.

그렇다고 해도 constructor라고는 할 수는 없습니다. new ConTest()했을때 실행이 되는 것이 아니라, ConTest().ConTest()해야지만 실행이 되니까요.

----
I paint objects as I think them, not as I see them.
atie's minipage