참조변수 super

essential·2023년 7월 16일

객체 지향

목록 보기
20/40

참조변수 super

  • 객체 자신을 가리키는 참조변수. 인스턴스 메서드(생성자)내에만 존재 (static 메서드내에서 사용 불가)
  • 조상의 멤버를 자신의 멤버와 구별할 때 사용
class Ex7_2 {
	public static void main(String args[]) {
			Child c = new Child();
			c.method();
	}
}

class Parent { int x = 10; //super.x}

class Child extends Parent {
	int x = 20; //this.x 
	
	void method() {
			System.out.println("x=" + x);
			System.out.println("this.x=" + this.x);
			System.out.println("super.x=" + super.x);
	}
}

//결과 x=20
//결과 this.x=20
//결과 super.x=10
class Ex7_3 {
	public static void main(String args[]) {
			Child c = new Child();
			c.method();
	}
}

class Parent { int x = 10; //super.x와 this.x 둘다 가능}

class Child extends Parent {	
	void method() {
			System.out.println("x=" + x);
			System.out.println("this.x=" + this.x);
			System.out.println("super.x=" + super.x);
	}
}

//결과 x=10
//결과 this.x=10
//결과 super.x=10

super() - 조상의 생성자

  • 조상의 생성자를 호출할 때 사용
  • 조상의 멤버는 조상의 생성자를 호출해서 초기화
  • 생성자의 첫 줄에 반드시 생성자를 호출해야 한다. 그렇지 않으면 컴파일러가 생성자의 첫 줄에 super(); 를 삽입
class Point {
	int x,y;
	
	Point(int x, int y) {
			this.x = x; //iv 초기화
			this.y = y; //iv 초기화
	}
}

class Point3D extends Point {
	int z;
	
	Point3D(int x, int y, int z) { // 
		super(x,y); //조상클래스의 생성자 Point(int x, int y)를 호출해서 초기화 시킴
		this.z = z; //자신의 멤버를 초기화
	}
}
class Point {
	int x;
	int y;
	
	Point() {
			this(0,0); // ㅇㅇ 생성자 호출중
	}

	Point(int x, int y) {
			this.x = x; // 생성자 호출이 아님 여기에 super(); 를 넣음 컴파일러가 
			this.y = y;
	}
}

//--- 컴파일 하면 ---
class Point extend Object{
	int x;
	int y;
	
	Point() {
			this(0,0); // ㅇㅇ 생성자 호출중
	}

	Point(int x, int y) {
			super(); // Object();
			this.x = x; 
			this.y = y;
	}
}

ex.super()

class Point {
	int x;
	int y;

	Point(int x, int y) {
//생성자 호출 안해서 컴파일러가 super(); 넣어서 Object()호출
			this.x = x;
			this.y = y;
	}
	String getLocation() {
			return "x : "+ x + ", y : " + y;

	}
}
class Point3D extends Point {
		int z;
		
		Point3D(int x, int y, int z) {
//생성자 호출 안해서 컴파일러가 super(); 넣어서 Point()호출
			this.x = x;
				this.x = x;
				this.y = y;
				this.z = z;
		}
		String getLocation() { //오버라이딩
			return "x : "+ x + ", y : " + y + ",z : " + z;
		}
}

class PointTest { 
		public static void main(string args[]) {
				Point3D p3 = new Point3D(1,2,3);
		}
}

Point () < 이 생성자가 없어서 (기본 생성자) 에러남 supber(Object(); 는 있지만)

Point3D(int x, int y, int z) {

super(x,y); //조상의 생성자 Point(int x, int y)를 호출 this.z = z;

}

이렇게 수정하면 컴파일 에러 안남

profile
essential

0개의 댓글