super的使用

来源:互联网 发布:淘宝人工客服打不进去 编辑:程序博客网 时间:2024/06/05 21:06
//在类中使用super的示例class Father{void speak(){System.out.println("I am Father.");}void speak(String s){System.out.println("I like " + s + ".");}}class Son extends Father{void speak(){System.out.println("My father says.");super.speak();//相当于调用Father类的speak()方法super.speak("hunting");//相当于调用Father类的speak(String s)方法}}public class Solution {public static void main(String args[]){Son s = new Son();s.speak();}}

执行结果是:

My father says.
I am Father.
I like hunting.

super用来取用父类中的方法和变量数据。

使用父类的变量形式也很类似:super.变量名

super和this的另一个重要用途是用在构造方法中。当一个类中不止一个构造方法时,可以用this在一个构造方法中调用中一个构造方法。若想调用父类的构造函数,则直接使用super。例如类Rectangle的子类ColorRectangle:

public class ColorRectaqngle extends Rectangle{   int color;   ColorRectangle(int w,int h,int c){    super(w,h);    color=c;   }   ...  }

与父类Rectangle相比,类ColorRectangle增加了color成员变量代表长方形的颜色。在它的构造方法中,用语句
    super(w,h);
调用了类Rectangle的构造方法
    Rectangle(int w,int h);
设定长方形的长和宽,然后就只需设定长方形的颜色:
    color=c;
这样大大提高了代码的重用性。


0 0