栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA上机任务八(泛型)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA上机任务八(泛型)

泛型

泛型是带一个或多个类型参数(type parameters)的类或者接口, 其声明的格式为:

                                        class 类名称<泛型列表>

泛型列表中可以有任意多个泛型,中间用逗号间隔,它们可以是任何 类或接口,但不能是基本类型数据。

第一题

源代码:

public class shangji08 {
    public static class People {
        private E pets;
        void set(E e){
            this.pets = e;
        }
        E showPets(){
            return pets;
        }
    }
    public static class Dog {
        String name ;
        Dog(String name){
            this.name = name;
        }
    }
    public static class Cat {
        String name ;
        Cat(String name){
            this.name = name;
        }
    }
    public static void main(String[] args) {
        People dog = new People();
        dog.set(new Dog("xiugou"));
        System.out.println("The name of this pet is " + dog.showPets().name);
        People cat = new People();
        cat.set(new Cat("maomao"));
        System.out.println("The name of this pet is " + cat.showPets().name);
    }
}
第二题

源代码:

import java.util.LinkedList;

public class shangji0802{
    public static void main(String[] args) {
        Player bofangqi = new Player();
        Song s1 = new Song("我是老6", "wjh");
        Song s2 = new Song("姬霓太美", "刀刀");
        bofangqi.addSong(s1);
        bofangqi.play(1);
        bofangqi.addSong(s2);
        bofangqi.play(2);
        bofangqi.removeSong(2);
        bofangqi.play(2);
    }
}
class Player{
    LinkedList songList = new LinkedList<>();
    void addSong(Song s){
        songList.add(s);
    }
    void removeSong(int i ){
        songList.remove(i-1);
    }
    void play(int i){
        if (i > songList.size()){
            System.out.println("超出歌单长度!");
        }
        else {
            System.out.println("第" + i + "首歌的歌手为:" + songList.get(i-1).singer + "   歌名为:" +songList.get(i-1).name);
        }
    }
}
class Song{
    String name;
    String singer;
    public Song(String name, String singer) {
        this.name = name;
        this.singer = singer;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/930218.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号