this和super的区别

this和super的区别:

     this和super分别是什么哪?

              this表示本类的引用,super可以表示为父类存储空间的标示,(可以理解为父类的引用,可以操作父类的成员)。

      怎么用呢?

               A:调用成员变量

                          this.成员变量  调用本类的成员变量

                          super.成员变量  调用父类的成员变量

               B:调用构造方法

                           this(......)   调用本类构造方法         

         super(....)  调用父类构造方法

                C:调用成员方法

                           this.成员方法     调用本类的成员方法

                           super.成员方法     调用父类的成员方法

this 调用成员方法示例:

class  Prent {
    public Prent(){}
    public int num = 10;

}

class  Son extends Prent{
    int num = 20;
    public void show(){
        int num = 30;
        System.out.println(num);            //调用局部变量
        System.out.println(this.num);      //调用本类成员变量
        System.out.println(super.num);     //调用父类成员变量
    }
}

public class this_gouzao {
    public static void main(String[] args) {
        Son s = new Son();
        s.show();
    }
}
//结果:
//30
//20
//10

this构造方法,继承中构造方法关系:

  若我们不想给父类无参构造,但还想调用父类中有参构造,怎么办呢?

         这时我们可以super(....);方法调用父类中的有参构造函数,同样的,调用时也会对父类进行初始化。

           也可以使用this();方法。

 
 
 
class  Father {
 
//    public Father(){
//        System.out.println("Father的无参构造方法");
//    }
    public Father(String name){
        System.out.println("Father的有参构造方法");
    }
 
 
}
 
class Son extends Father{
 
    public Son(){
        super("linqingxia");
        System.out.println("Son的无参构造方法");
    }
 
    public Son(String name){
       this(); //  super("linqingxia");也可以用this来调用本类中的无参构造,但用this的前提是子类无参构造中含有super(.....);方法
        System.out.println("Son的有参构造方法");
    }
}
 
 
public class jicheng_biduan {
    public static void main(String[] args) {
       Son son = new Son();
        System.out.println("---------------------");
        Son s2=new Son("王祖贤");
 
    }
}

this调用成员方法:

class  Father {

    public void show2(){
        System.out.println("AAA");
    }
}

class Son extends Father{

    public void show(){
        System.out.println("aaa");
        super.show2();
        this.show2();
    }
}


public class  this_gouzao {
    public static void main(String[] args) {
        Son son = new Son();
        son.show();
    }
}

//运行结果:
//aaa
//AAA
//AAA

 

posted @ 2019-04-26 08:08  LOL_toulan  阅读(531)  评论(0编辑  收藏  举报