super(a)参数a在Java里怎么用

解释super用法

super 是用来调用父类中的方法的。
1. 在子类的构造函数之中调用父类的构造函数, super(参数列表) 将会调用父类的构造函数, 该语句必须是子类构造函数的第一句。
2. 在子类的非构造函数之中调用父类的非构造函数(此处不能调用父类的构造函数), 用法: super.方法名(参数列表)。 如下面的:super.toString()是调用的父类之中的toString() 方法。
如下,一个具体的例子:
class Father {
private int val;
public Father(int a) {
val = a;
}
public int getValue() {
return val;
}
public String toString() {
return "FatherValue = " + val;
}
}
class Child extends Father {
int myValue;
public Child(int a) {
super(a); //调用Father类的构造方法,其只能在刚构造函数的第一句。
myValue = a+3;
}
public String toString() {
String s = super.toString(); //调用Father类之中的toString()方法。
return s + " ChildValue = " + myValue;
}
}

public class Test6 {
public static void main(String [] args) {
Child child = new Child(5);
System.out.println(child.toString());
}
}
最后的输出结果:
FatherValue = 5 ChildValue = 8追问

class WindowButton extends Frame
{
int number;
Label label1;
TextField text1;
Button buttonGetNumber,buttonEnter;
WindowButton(String s)
{
super(s);那这个具体要怎么解释 它没有子类啊 只是主函数里传来的
}
}
public class ButtonDemo
{
public static void main(String args[])
{
WindowButton win=new WindowButton("窗口");
}
}

追答

WindowButton(String s)
{
super(s);那这个具体要怎么解释 它没有子类啊 只是主函数里传来的
}

这儿的WindowButton类本身是Frame的一个子类, 此处的super(s)是调用的Frame的构造方法Frame(String)

温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-11-30
super(a)的正确解释是
在子类中调用super(a)就是调用父类的构造方法,比如父类的类名是Stu,父类中有一个构造方法public Stu(int a ),那么在子类中super(a)就是调用了这个方法,父类中可以有多个构造方法,不过它要根据调用的参数就行重载方法。