자바 에서 this 와 슈퍼 키워드 상세 설명
14226 단어 자바 기초 문법
this 키워드, this 는 대상 자 체 를 가리 키 며, 하나의 클래스 는 this 를 통 해 자신 을 대표 하 는 대상 변 수 를 얻 을 수 있 습 니 다.this 는 다음 세 가지 상황 에 사 용 됩 니 다.
this 변수의 예제 코드 를 사용 합 니 다:
public class Person {
//
private String name;
//
private int age;
//
private Date birthDate;
//
public Person(String name, int age, Date d) {
this.name = name;
this.age = age;
birthDate = d;
System.out.println(this.toString());
}
public Person(String name, int age) {
//
this(name, age, null);
}
public Person(String name, Date d) {
//
this(name, 30, d);
}
public Person(String name) {
// System.out.println(this.toString());
// Person(String name, Date d) ,
this(name, null);
}
@Override
public String toString() {
return "Person [name=" + name
+ ", age=" + age
+ ", birthDate=" + birthDate + "]";
}
}
주의: this 를 사용 하여 다른 구조 방법 을 호출 할 때 this 문 구 는 반드시 이 구조 방법의 첫 번 째 문구 입 니 다.
슈퍼 키워드
슈퍼 키 워드 는 현재 대상 의 초 클래스 대상 을 가리킨다.즉, 현재 대상 의 부모 클래스 대상 입 니 다.슈퍼 키 워드 는 일반적으로 하위 클래스 에 사용 된다.슈퍼 키워드 의 역할:
부모 클래스 Person 코드 는 다음 과 같 습 니 다:
public class Person {
//
private String name;
//
private int age;
//
private Date birthDate;
//
public Person(String name, int age, Date d) {
this.name = name;
this.age = age;
birthDate = d;
System.out.println(this.toString());
}
public Person(String name, int age) {
//
this(name, age, null);
}
public Person(String name, Date d) {
//
this(name, 30, d);
}
public Person(String name) {
// System.out.println(this.toString());
// Person(String name, Date d) ,
this(name, null);
}
}
하위 클래스 Student 코드 는 다음 과 같 습 니 다.
public class Student extends Person {
//
private String school;
public Student(String name, int age, Date d, String school) {
super(name, age, d);
this.school = school;
}
public Student(String name, int age, String school) {
// this.school = school;//
super(name, age);
this.school = school;
}
public Student(String name, String school) {
// 3
// super(name, 30);
this.school = school;
}
}
주의: 슈퍼 문 구 는 하위 구조 방법의 첫 줄 에 있어 야 합 니 다.
코드 ③ 줄 구조 방법 은 슈퍼 구문 이 없 기 때문에 컴 파일 러 는 부모 류 의 기본 구조 방법 (매개 변수 구조 방법 없 음) 을 호출 하려 고 하지만 부모 류 Person 은 기본 구조 방법 이 없 기 때문에 컴 파일 오류 가 발생 할 수 있 습 니 다.이 컴 파일 오 류 를 해결 하 는 데 는 세 가지 방법 이 있다.
슈퍼 와 this 의 공통점:
이상 의 내용 은 참고 학습 만 제공 합 니 다. 권리 침해 가 있 으 면 저 에 게 연락 하여 삭제 하 십시오!이 글 이 당신 에 게 도움 이 된다 면 왼쪽 아래 엄지손가락 은 블 로 거들 에 게 가장 큰 격려 입 니 다.당신 의 격려 는 블 로 거들 의 가장 큰 동력 입 니 다!