public class Super extends Father{ public static void main(String args[]){ Super s = new Super(); Super ss = new Super(2); } public Super(){ super(10); System.out.println("调用子类构造方法"); } public Super(int i){ System.out.println("?");//此处第一行隐藏了super(); } } class Father{ int p; public Father(){ } public Father(int p){ System.out.println("调用父类中的有参构造方法"); } }
运行结果如下:
如果删掉public Father(){}那么此处将要报错,因为系统找不Father类的构造方法,
public Super(int i){ System.out.println("?");//此处第一行隐藏了super(); }
另外在子类构造方法中不一定要继承父类的构造方法,那么就需要将this()放在子类构造方法的第一行,如果将代码改成如下:
public Super(int i){ this(); System.out.println("?");//此处第一行隐藏了super(); }
由上述结果可知this()代表调用本类构造方法,也可以在()加参数
public class Super extends Father{ String name; int age; public static void main(String args[]){ Super s = new Super("dog",15,"tiger",20); System.out.println(s.name); System.out.println(s.age); s.output(); } public Super(String name,int age,String name1 ,int age1){ this.name = name; this.age = age; super.name = name1; super.age = age1; } public void output(){ System.out.println(super.name); System.out.println(super.age); super.compare(this.name, this.age, super.name, super.age); } } class Father{ String name; int age; Father(){ } public void compare(String name,int age,String name1,int age1){ System.out.println(name+"的年龄比"+name1+(age1>age?'小':'大')); } }
上述代码说明在子类成员方法中存着父类的地址