본문 바로가기

카테고리 없음

[JAVA] 생성자와 상속

1
2
3
4
5
6
7
package a;
 
public class ConstructorDemo {
    public static void main(String[] args) {
        ConstructorDemo  c = new ConstructorDemo();
    }
}

cs 


위의 예제는 에러를 발생시키지 않는다. ConstructorDemo 객체를 생성할 때 자동으로 

생성자를 만들어주기 때문이다


1
2
3
4
5
6
7
8
package a;
 
public class ConstructorDemo {
    public ConstructorDemo(int param1) {}
    public static void main(String[] args) {
        ConstructorDemo  c = new ConstructorDemo();
    }
}
cs


이 예제는 에러를 발생시킨다. 에러가 발생되는 이유는 매개변수가 있는 생성자가 있을 때는 자동으로 기본 생성자를 만들어주지 않기 때문이다.


1
2
3
4
5
6
7
public class ConstructorDemo {
    public ConstructorDemo(){}
    public ConstructorDemo(int param1) {}
    public static void main(String[] args) {
        ConstructorDemo  c = new ConstructorDemo();
    }
}
cs


위 예제와 같이 매개변수가 없는 생성자를 생성하면 인스턴스를 생성 할 수 있다.


출처:https://opentutorials.org/course/1223/6126