super, super()
reference type variable super, constructor super()
super
reference type variable that indicates itself.
exist within instance method(constructor).
distinguish parent members between current members
class Parent {int x = 10;}
class Child extens Parent {
int x = 20;
void omethod() {
System.out.prinln("x=" - x);
System.out.prinln("this.x=" + this.x);
System.out.prinln("super.x=" + super.x);
}
}
super() : parent constructor
call parent constructor
initialize parent member by calling parent constructor
add constructor in the first line otherwise compiler adds super(); automatically. 모든 생성자는 첫 줄에 다른 생성자를 호출해야한다. 그렇지 않으면 컴파일러가 자동으로 super()를 호출해버린다.
class Point {
int x,y;
Point() {
this(0,0);//constructor in first line
}
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
class Point3D extends Point {
int z;
Point 3D(int x, int y, int z) {
super(x,y);
this.z = z;
}
}
class Point{
int x,y;
Point(int x, int y) {
//no constructor in first line
//=>compiler will add super();
this.x = x;
this.y = y;
}
}
class Point3D extends Point {
int z;
Point3D(int x, int y, int z) {
super(x,y);//call parent constructor super()
this.z = z;
//this.x = x;
//this.y = y;
}
}
right code below :
default constructor in Point class
must call other constructor in first line
super constructor in Point3D constructor
class Point {
int x;
int y;
//1. default constructor
Point() {}
Point(int x, int y) {
//2. must call other constructor in first line
Point(){};
this.x = x;
this.y = y;
}
}
class Point3D extends Point {
int z;
Point3D(int x, int y, int z) {
Point(x,y);
this.z = z;
}
}
Last updated
Was this helpful?