Javaリファレンス変数super


参照変数super

  • 参照変数はこれに似ています.(lv、ivを区別するための)
  • オブジェクト自体への参照変数
  • .
  • は、インスタンスメソッド(作成者)にのみ存在する.
  • を使用して、祖先のメンバーと自分のメンバーを区別します.
    public class EX7_3 {
        public static void main(String[] args) {
            Child child = new Child();
            child.method();
        }
    }
    
    class Parent{
        int x = 10; // super
    }
    
    class Child extends Parent{
        int x = 20; // this
        void method(){
            System.out.println("x= " + x); // x= 20
            System.out.println("this.x= " + this.x); // this.x= 20
            System.out.println("super.x= " + super.x); // super.x= 10
        }
    }

    super():祖先の創造者

  • this()
  • と同様
  • 祖先の作成者を呼び出すときに
  • を使用します.
  • 祖先のメンバーは、祖先の作成者を呼び出すことによって
  • を初期化する.
    class MyPoint{
        int x, y;
        MyPoint(int x, int y){
            this.x = x;
            this.y = y;
        }
    }
    
    class MyPoint3D extends MyPoint{
        int z;
        
        MyPoint3D(int x, int y, int z){
            this.x = x; // 조상의 멤버를 초기화
            this.y = y; // 조상의 멤버를 초기화
            this.z = z;
        }
        // There is no default constructor available in 'MyPoint'
        // 조상의 멤버는 super()로 초기화 해주는게 맞다.
    }
  • 正しく変更(super()を使用)
  • class MyPoint{
        int x, y;
        MyPoint(int x, int y){
            this.x = x;
            this.y = y;
        }
    }
    
    class MyPoint3D extends MyPoint{
        int z;
    
        MyPoint3D(int x, int y, int z){
            super(x, y); // MyPoint(x, y)와 같은 의미
    //        this.x = x; // 조상의 멤버를 초기화
    //        this.y = y; // 조상의 멤버를 초기화
            this.z = z;
        }
        // There is no default constructor available in 'MyPoint'
        // 조상의 멤버는 super()로 초기화 해주는게 맞다.
    } 
  • ジェネレータの最初の行は、ジェネレータを呼び出す必要があります.そうでなければ、コンパイラは、ジェネレータの最初の行にsuper();を挿入します.