DemoSuper: Name=kevin Age=22
这样的使用方法是比较常用的。另外如果父类的成员可以被子类访问,那你可以像使用this一样使用它,用“super.父类中的成员名”的方式,但常常你并不是这样来访问父类中的成员名的。
在构造函数中
构造函数是一种特殊的方法,在对象初始化的时候自动调用。在构造函数中,this和super也有上面说的种种使用方式,并且它还有特殊的地方,请看下面的例子:
class Person{ public static void prt(String s){ System.out.println(s); } Person(){ prt("A Person."); } Person(String name){ prt("A person name is:"+name); } } public class Chinese extends Person{ Chinese(){ super(); //调用父类构造函数(1) prt("A chinese.");//(4) } Chinese(String name){ super(name);//调用父类具有相同形参的构造函数(2) prt("his name is:"+name); } Chinese(String name,int age){ this(name);//调用当前具有相同形参的构造函数(3) prt("his age is:"+age); } public static void main(String[] args){ Chinese cn=new Chinese(); cn=new Chinese("kevin"); cn=new Chinese("kevin",22); } }
(编辑:aniston)
|