컴퓨터 공부/JAVA

[JAVA] this와 this() ,super과 super의 차이점

나정_ 2012. 3. 26. 13:15

this와 this() 그리고 super과 super()은 보기에 유사하지만 사용방법이 전혀 다르다 . 




우선 this와 this()의 차이점은 

this란  현재 객체 자신을 의미하는 참조변수이고  this()란 현재 객체내의 생성자를 의미한다. 


자세하게 설명을 하자면 


this


1) this의 정의 

자기 자신을 의미하는 참조변수 


2) this의 특징 

- 매개 변수와 객체 자신이 가지고 있는 변수의 이름이 같은 경우 이를 구분하기 위해 this를 사용한다. 


3) 예제

ex) 
public class Najung { 
int age ; 
public void getInfo(int age) { 
this.age = age ; }
}   

  

this()


1) this()의 정의 

객체 내의 생성자를 호출


2) this의 특징 

-  객체 생성자에서 사용시 다른 생성자를 호출한다. 


3) 예제 

class This_1 {

 int i ,double d;

 public This_1(int i){ 

  this(3.14); 

 System.out.println(i); 

 } 

 public This_1(double d){ 

 System.out.println(d); 

 } 

public static void main(String[] args) {

This_1 t=new This_1(100); 

}


*  유의사항 

- this()는 맨 윗줄에 적어야 한다. 

- static메소드에서 사용할 수 없다. 




두번째로 super과 super()의 차이점은 

super은  부모클래스의 변수나, 메소드를 사용하기 위한 변수호출이고  super()란 부모클래스의 생성자를 호출을 의미한다. 


super

1) super의 특징 

- 자식 클래스에서 부모 클래스의 변수나, 메소드를 호출하기위해 사용한다.  

2) 예제 

1 : class Dad{ 


2 :      int i=1000; 

3 :    public String Method2(){ 

4 :      String s="상위 메소드이에요.."; 

5 :      return s; 

6 :    } 

7 : } 

8 : class Super_1 extends Dad{ 

             int i=20; 

9 :    public int Method1(){ 

10 :      return super.i; //상위 클래스의 멤버변수 호출

11 :    } 

12 :    public String Method2(){ 

13 :      return super.Method2(); //상위 클래스의 메서드 호출

14 :    } 

15 :    public static void main(String[] args) 

16 :    { 

17 :      Super_1 aa=new Super_1(); 

18 :      System.out.println(aa.Method1()); 

19 :      System.out.println(aa.Method2()); 

20 :    } 

21 : }

[출처] 자바의 this와 super|작성자 하루


super()

1) super()의 특징 

-부모 클래스의 생성자를 호출할 때 사용하며 상속시 생성자의 문제를 해결한다. 

2) 예제 

1 : class A
2 : { 
3 :    public A(String s){
4 :      System.out.println("상위클래스 생성자!");
5 :    }
6 : }
7 : class Super_2 extends A{
8 :    public Super_2(){
9 :      super("fddsf");
10 :      System.out.println("하위클래스 생성자!");
11 :   }
12 :    public static void main(String[] args) {
13 :      Super_2 b=new Super_2(); 
14 :      System.out.println("메인!");
15 :    }
16 : }
[출처] 자바의 this와 super|작성자 하루

'컴퓨터 공부 > JAVA' 카테고리의 다른 글

[JAVA] 정규식을 배워보자 (1)  (2) 2013.03.29
[JAVA] arrayList와 linkedList 차이점  (2) 2013.03.15
[JAVA] compareTo, equal, == 의 차이점  (5) 2013.02.08
Vector-벡터  (0) 2012.04.05
[기타]data/heap/stack/메모리 구조  (2) 2012.03.30