java继承与多态之this和super

来源:互联网 发布:linux运维入门 编辑:程序博客网 时间:2024/06/05 01:39

在解释this和super的区别之前先说一下方法的重写(Override)和重载(OverLoad)

       方法的重写(Override):在子类中,出现和父类一模一样方法声明的现象

public class Person{private String name;private int age;private String hobby;public void show(){System.out.println("姓名:" + name + " 年龄:" + age + " 爱好:" + hobby);}}public class Student extends Person{private int score;public void show(){System.out.println("姓名:" + name + " 年龄:" + age + " 爱好:" + hobby + " 分数:" + score);}}


在子类Student类中声明了一个和父类Person类相同的show()方法,因此构成了方法的重写

         方法的重载(OverLoad):在本类中,出现方法名相同,参数列表不同的现象(跟返回值无关)

public class Student extends Person{private int score;public void show(){System.out.println("姓名:" + name + " 年龄:" + age + " 爱好:" + hobby + " 分数:" + score);}public void show(int score){System.out.println("姓名:" + name + " 年龄:" + age + " 爱好:" + hobby + " 分数:" + score);}}


在Student类中存在两个方法名同为show的方法声明,但是两个方法参数列表不同,因此构成了方法的重载

this和super

       this:本类数据的引用

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

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

              this.method(..) 调用本类的成员方法

public class Person{private String name;private int age;private String hobby;public int num = 10;public Person(){}public Person(String name, int age){this.name = name; //调用本类的成员变量this.age = age;}public Person(String name, int age, String hobby){this(name, age); //调用本类带两个参数的构造方法this.hobby = hobby;}public void show(){System.out.prinltn("Person");}}

       super:代表存储空间的标识(可以理解为父类的引用)

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

              super(..)  调用父类的构造函数

              super.method(..)  调用父类的成员方法

public class Person{private String name;private int age;private String hobby;public int num = 10;public Person(){}public Person(String name, int age){this.name = name; //调用本类的成员变量this.age = age;}public Person(String name, int age, String hobby){this(name, age); //调用本类带两个参数的构造方法this.hobby = hobby;}public void show(){System.out.prinltn("Person");}}public class Student extends Person{private int score;private int num = 20;public Student(String name, int age, String hobby){super(name, age, hobby); //调用父类的带参构造}public void method(){int num = 30;System.out.println("Person的num" + super.num);//调用父类Person成员变量num = 10System.out.println("Student的num" + this.num);//调用本类Student成员变量num = 20System.out.println("method的num" + num);//调用method的局部变量num = 30}public void show(){super.show();//调用父类Person的show()方法System.out.prinltn("Person");}}


   注意:

              1、在子类的构造方法中会默认调用父类的无参构造方法,这是因为子类继承了父类的成员,而且可能会用到父类的成员,所以需要调用父类无参构造对成员进行初始化。

              2、this(..)super(..)必须出现在第一条语句

原创粉丝点击