참조변수 super
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() - 조상의 생성자
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;
}
이렇게 수정하면 컴파일 에러 안남