개발/JAVA
super super()
에크키키
2022. 7. 12. 15:09
참조변수 super
자손클래스에서 조상클래스로부터 상속받은 멤버를 참조하는데 사용되는 참조변수
상속받은 멤버와 자신의 멤버의 이름이 같을때 구분을위해 사용
this와 마찬가지로 static메서드에서 사용불가
조상클래스의 메서드를 오버라이딩한경우에 super사용
class SuperTest2 {
public static void main(String args[]) {
Child c= new Child();
c.method();
}
}
class Parent{
int x =10;
}
class Child extends Parent{
int x= 20;
void method() {
System.out.println("x="+x); //20
System.out.println("this.x="+this.x);//20
System.out.println("super.x="+super.x);//10
}
}
class point{
int x;
int y;
String getLocation() {
return "x:"+x+",y:"+y;
}
}
class point3D extends point{
int z;
String getLocation() { // 오버라이딩
return super.getLocation()+"z,:"+z; //조상의 메서드 호출
}
}
super()
조상클래스의 생성자를 호출
※object클래스를 제외한 모든클래스의 생성자는 첫줄에 반드시 자신의 다른생성자this() 또는
조상의 생성자super()를 호출해야 한다.
public class PointTest2 {
public static void main(String[] args) {
Point3D p3=new Point3D();
System.out.println("p3.x="+p3.x);
System.out.println("p3.y="+p3.y);
System.out.println("p3.z="+p3.z);
}
}
class Point extend Object{ //최고 조상 object
int x =10;
int y =20;
Point(int x, int y) {
super(); //object의 생성자 호출
this.x=x;
this.y=y;
}
}
class Point3D extends Point{
int z=30;
Point3D() {
this(100,200,300); //point3D(int x, int y, int z)를 호출한다.
}
Point3D(int x, int y, int z){
super(x,y); //point(int x, int y)를 호출한다.
this.z=z;
}
}
모든 자식생성자가 생성될때는 자동으로 "부모의 기본 생성자"를 호출한다.
그러나 부모클래스가 매개변수가 있는 생성자를 선언하면, 자바는 자동으로 기본생성자를 생성하지 않기 때문에
자식생성자는 부모생성자를 호출할 수 없고 에러가 발생하게됨
해결방법
1. 부모클래스에 기본생성자를 만들어주거나
2. 부모클래스에 인자가 있는 또다른 생성자인 super()를 자식클래스에 불러옴
=> 현업에서는 대부분 2번을 사용!!
[출처] 상속과 생성자: super()|작성자 탱