您的位置:首页 > 其它

验证

2015-11-09 21:18 309 查看
1.通过super()调用父类的有参构造方法,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");

}

}

class Child extends Parent

{ public Child()

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

}

public class TestInherits

{public static void main(String args[])

{Child c = new Child();}

}



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");

}

}

class Child extends Parent

{ public Child()

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

}

public class TestInherits

{public static void main(String args[])

{Child c = new Child();}

}



public class ExplorationJDKSource {

/**

* @param args

*/

public static void main(String[] args) {

System.out.println(new A());

}

}

class A{}



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

package com;

class Country

{

String name;

void value()

{

name="Chine";

}

}

class City extends Country

{

String name;

void value()

{

name="hebei";

super.value();

System.out.println(name);

System.out.println(super.name);

}

}

public class T {

public static void main(String[] args) {

// TODO Auto-generated method stub

City c=new City();

c.value();

}



为了在子类中引用父类中的成员变量和方法value(),在代码中使用了super,super.name,super.value(),若不调用super.value()时,super.name返回的是父类成员的默认值null,调用方法时,super.value()方法先把成员变量name赋值为china,再用super.name调用父类成员变量的值。

继承与接口

package com;

interface Flyanimal

{void fly();}

class Insect

{

int legnum=6;

}

class Bird

{

int legnum=2;

void egg(){};

}

class Ant extends Insect implements Flyanimal

{

public void fly()

{System.out.println("Ant can fly");}

}

class Pigeon extends Bird implements Flyanimal

{

public void fly()

{System.out.println("Pigegon can fly");}

public void egg()

{System.out.println("Pigegon can lay eggs");}

}

public class T1 {

public static void main(String[] args) {

// TODO Auto-generated method stub

Ant a=new Ant();

a.fly();

System.out.println("Ant's legnum is"+a.legnum);

Pigeon p=new Pigeon();

p.fly();

p.egg();

}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: