美文网首页
NO.14 this和super的区别与使用

NO.14 this和super的区别与使用

作者: WXFA | 来源:发表于2017-07-23 22:06 被阅读0次

this和super都代表什么

              this:代表当前对象的引用,谁来调用我,我就代表谁

               super:代表当前对象父类的引用

this和super的使用区别

        调用成员变量

                 this.成员变量 调用本类的成员变量,也可以调用父类的成员变量

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

         调用构造方法(只能有一个出现在同一语句中)

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

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

         调用成员方法

                    this.成员方法 调用本类的成员方法,也可以调用父类的方法

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

public static void main(String[] args) {

//Son s1 = new Son();

System.out.println("............");

Son s = new Son("张三",23);

System.out.println(s.getName() + "...." + s2.getAge());

}

}

class Father {

private String name;

private int age;

/*public Father() {

System.out.println("Father  类的空参构造");

}*/

public Father(String name,int age) {

this.name = name;

this.age = age;

System.out.println("Father  类的有参构造");

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

}

class Son extends Father {

/*public Son() {

* this("王五", 25);          //子类无参构造this()语句访问,调用本类的构造方法,执行父类的有参构造

* super("李四",24);        //子类无参构造super()语句访问父类的有参构造,调用父类的构造方法

System.out.println("Son  类的无参构造");

}*/

public Son(String name,int age) {    //子类有参构造访问父类的有参构造

super(name,age);

System.out.println("Son  类的有参构造");

}

}

相关文章

网友评论

      本文标题:NO.14 this和super的区别与使用

      本文链接:https://www.haomeiwen.com/subject/egjmkxtx.html