java中super关键字

1.子类的构造函数如果要引用super的话,必须把super放在函数的首位,如果想用super继承父类构造的方法,但是没有放在第一行的话,那么在super之前的语句,肯定是为了满足自己想要完成某些行为的语句,但是又用了super继承父类的构造方法。那么以前所做的修改就都回到以前了,就是说又成了父类的构造方法了。

2. 在Java中,有时还会遇到子类中的成员变量或方法与父类中的成员变量或方法同名。因为子类中的成员变量或方法名优先级高,所以子类中的同名成员变量或方法就隐藏了父类的成员变量或方法,但是我们如果想要使用父类中的这个成员变量或方法,就需要用到super。

3.super(参数):调用基类中的某一个构造函数(应该为构造函数中的第一条语句)。

例如:


class Grandparent {


public Grandparent() {

System.out.println("GrandParent Created.");

}


public Grandparent(String string) {

System.out.println("GrandParent Created.String:" + string);

}

}


class Parent extends Grandparent {


public Parent() {

super("Hello.Grandparent.");

System.out.println("Parent Created");

//super("Hello.Grandparent.");

}

}


class Child extends Parent {


public Child() {

System.out.println("Child Created");

}

}


public class TestInherits {


public static void main(String args[]) {

Child c = new Child();

}

}

posted @ 2015-11-03 16:36  梦玄庭  阅读(209)  评论(0编辑  收藏  举报