java中super的運用

   super可以在子類中調用父類的構造方法,省下很多代碼。例如:

   abstract class Animal

{

   public String name;

   public int age;

   public int weight;

  Animal(String aname,int aage,int aweight)

  {

      name = aname;

      age = aage;

      weight = aweight;

   }

  public void showInfo(){

   System.out.println("名字:"+name+" 年齡:"+age+" 體重:"+weight);

  }

   abstract void move();

   abstract void eat();

}

class Fish extends Animal

{

   String name;

   int age;

   int weight;

   Fish(String name,int age,int weight)

   {

        super(name,age,weight);

    }

  void move(){

    System.out.println("Fish move()");

    }

  void eat(){

    System.out.println("Fish eat()");

    }

}

public class TestAnimal

{

   public static void main(String args[])

{

   Fish fish = new Fish("seafish",2,10);

   fish.move();

   fish.eat();

   fish.showInfo();

}

}

運行結果:Fish move()

          Fish eat()

         名字:seafish 年齡:2 體重:10

類fish不能再定義showInfo(),不然會認爲子類要重載,會出錯。子類中的成員變量或方法名優先級高,子類的同名成員變量或方法就隱藏了父類的成員變量或方法,如果想要使用父類中的這個成員變量或方法,就需要用到super.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章