본문 바로가기

자바/클래스

상속 super

슈퍼클래스=상위클래스=부모클래스

서브클래스=하위클래스=자식클래스


예제1)


public class Test1 {

public static void main(String[] args) {

  Demo1 ob=new Demo1();

      ob.write();

}

}


class Ex1{

protected int x;

public Ex1(int x) {

this.x=x;

}

}


/*

class Demo1 extends Ex1 { =>디폴트 생성자를 호출한 셈이다. 그런데 상위클래스에는 디폴트생성자는 없고 인자가있는 생성자만 있다.

public void write(){

System.out.println(x);

}

}

*/


class Demo1 extends Ex1 {

public Demo1() {

super(10); 


System.out.println("서브 클래스 생성자");

}

public void write(){

System.out.println(x);

}

}


/*

 * 전체 설명

 * 상위클래스와 하위클래스의 상속관계가 존재하는 소스

 * 아버지에게는 인자가 있는 생성자가 있다

 * 자식에에게는 생성자가 없지만 없을때는 디폴트생성자 public Demo1()가 있는 상태와 동일하다.(생략한 상태를 말한다)

 * 결국 생성자는 상위,하위클래스 모두 있지만 아버지의 생성자 인수와 자식의 생성자 인수가 다르기 때문에 에러가 발생한다.

 * 아버지와 자식의 생성자 인수를 맞추기 위해서 public Demo1() {super(10)}; 를 사용한다.

 */


예제1 결과)

서브 클래스 생성자
10

========================================================================================================================================

예제2)

public class Test2 {
public static void main(String[] args) {
Demo2 ob=new Demo2();
ob.print();
Demo2 ob1=new Demo2(200);
ob1.print();
}
}

class Ex2 {
int x;
public Ex2() {
x=100;
System.out.println("super 인자 없는 생성자..");
}
public Ex2(int x) {
this.x=x;
System.out.println("super 인자 있는 생성자");
}
public void print(){
System.out.println("super:"+x);
}
}

class Demo2 extends Ex2{
int x=50;
public Demo2(){
}
public Demo2(int a){
super(a);
}
public void print(){
System.out.println(x); //자기꺼 x(50)
System.out.println(super.x); //슈퍼클래스의 x(100)
super.print();         //슈퍼클래스의 print메서드 호출
}
}

예제2 결과)

super 인자 없는 생성자..
50
100
super:100
super 인자 있는 생성자
50
200
super:200

'자바 > 클래스' 카테고리의 다른 글

인터페이스 interface  (0) 2013.05.21
abstract 클래스  (0) 2013.05.21
Scanner 클래스  (0) 2013.05.19
SimpleDateFormat  (0) 2013.05.19
Wrapper 클래스  (0) 2013.05.19