java中super的使用

来源:互联网 发布:自动回复聊天软件 编辑:程序博客网 时间:2024/05/21 13:58

一、super调用超类构造函数

super(parameter-list);

parameter-list指定超类中构造函数所需的任何形参,super()必须是在子类构造函数中执行的第一个语句。超类定义的任何形式的构造函数都可以被super()调用,被执行的构造函数就是与实参相匹配的那一个

当存在多重继承时,super总是引用最靠近的超类的构造函数。例如:C类继承B类,B类继承A类,则C类的构造函数中使用super,引用B类的构造函数。

如果不使用super(),那么就会执行每个超类的默认(无形参)构造函数。

例如:

public class test {public static void main(String [] args){new Teacher("one", 62);new Teacher("two", 180);new Teacher("three", 65, 188);}}class Human {static private float weight;static private int height;Human(float weight){Human.weight = weight;System.out.println(Human.weight);}Human(int height){Human.height = height;System.out.println(Human.height);}Human(float weight, int height){Human.weight = weight;Human.height = height;System.out.println(Human.weight + " " + Human.height);}}class Teacher extends Human {static private String s;Teacher(String s, float weight){super(weight);Teacher.s = s;System.out.println(Teacher.s);}Teacher(String s, int height){super(height);Teacher.s = s;System.out.println(Teacher.s);}Teacher(String s, float weight, int height){super(weight, height);Teacher.s = s;System.out.println(Teacher.s);}}
结果:

62
one
180
two
65.0 188
three


二、super访问超类的成员

例如:

public class test {public static void main(String [] args){new Teacher("three", 65, 188);}}class Human {static public float weight;static public int height;}class Teacher extends Human {static private String s;Teacher(String s, float weight, int height){super.weight = weight;super.height = height;Teacher.s = s;System.out.println(super.weight);System.out.println(super.height);System.out.println(Teacher.s);}}
结果:

65.0
188
three


三、super和this的区别

1)super(参数):调用基类中的某一个构造函数(应该为构造函数中的第一条语句);this(参数):调用本类中另一种形成的构造函数(应该为构造函数中的第一条语句);
2)super引用当前对象的直接父类中的成员(用来访问直接父类中被隐藏的父类中成员数据或函数,基类与派生类中有相同成员定义时如:super.变量名    super.成员函数据名(实参);this
代表当前对象名(在程序中易产生二义性之处,应使用this来指明当前对象;如果函数的形参与类中的成员数据同名,这时需用this来指明成员变量名);

3)调用super()必须写在子类构造方法的第一行,否则编译不通过。每个子类构造方法的第一条语句,都是隐含地调用super(),如果父类没有这种形式的构造函数,那么在编译的时候就会报错;super()和this()类似,区别是,super()从子类中调用父类的构造方法,this()在同一类内调用其它方法;

4)super()和this()均需放在构造方法内第一行;

5)尽管可以用this调用一个构造器,但却不能调用两个;

6)this和super不能同时出现在一个构造函数里面,因为this必然会调用其它的构造函数,其它的构造函数必然也会有super语句的存在,所以在同一个构造函数里面有相同的语句,就失去了语句的意义,编译器也不会通过;

7)this()和super()都指的是对象,所以,均不可以在static环境中使用。包括:static变量,static方法,static语句块;

8)从本质上讲,this是一个指向本对象的指针, 然而super是一个Java关键字。

参考之:http://blog.csdn.net/anmei2010/article/details/4093118


0 0
原创粉丝点击