集册 Java实例教程 从父级覆盖方法

从父级覆盖方法

欢马劈雪     最近更新时间:2020-01-02 10:19:05

499
从父级覆盖方法
/* 
 来自 
*时代Java - N o w  J a v a . c o m*/

import java.util.*;


class Cat extends Animal {


    public Cat() {

        super.setColor("white");

    }


    public static void hide() {

        System.out.format("The hide method in Cat.%n");

    }


    public void override() {/** 时 代 J a v a - nowjava.com 提 供 **/

        System.out.format("The override method in Cat.%n");

    }


    // Returns a litter of cats

    public Collection<Cat> getLitter(int size) {

        ArrayList<Cat> litter = new ArrayList<Cat>(size);

        for (int i = 0; i < size; i++)

            litter.add(i, new Cat());

        return litter;

    }


    public static void main(String[] args) {

        Cat myCat = new Cat();

        Animal myAnimal = myCat;

        Animal.hide();

        myAnimal.override();

    }

}


public class Cats {

    public static void main(String[] args) {

        Cat myCat = new Cat();

        Collection<Cat> litter = myCat.getLitter(3);

        for (Cat c : litter)

            System.out.format("%s%n", c.getColor());

    }

}


class Animal {

    private String color;


    public void setColor(String color) {

        this.color = color;

    }


    public String getColor() {

        return this.color;

    }


    public static void hide() {

        System.out.format("The hide method in Animal.%n");

    }


    public void override() {

        System.out.format("The override method in Animal.%n");

    }

}

展开阅读全文