慕移动7208282
2017-10-19 14:31
package com.imooc.collection;
/*
* 课程类
*
* */
public class Course {
private String id; //其实在实际开发中 应该把属性私有化 通过getter或者Setter来获取或者调用
private String name; //给两个属性 一个id属性 一个name属性
public Course(String id,String name){
this.id = id;
this.name = name;
}
public Course(){
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}package com.imooc.collection;
import java.util.ArrayList;
import java.util.List;
public class TestGeneric {
/*
* 带有泛型——Course,的List类型属性
* */
public List<Course> courses;
public TestGeneric(){ //构造器
this.courses = new ArrayList<Course>() ; //这里是要写出泛型的
}
/*
* 测试添加的方法
*
* */
public void testAdd(){
Course cr1 = new Course("1","大学语文");
courses.add(cr1);
//泛型集合中,不能添加泛型规定的类型及其子类型以外的对象,否则会报错
//courses.add("能否添加一些奇怪的东西呢???");
Course cr2 = new Course("2","java基础");
courses.add(cr2);
}
/*
* 测试循环遍历的方法
*
* */
public void testForEach(){
for (Course cr:courses){ //因为泛型定义了 所以和ListTest.java中写的不一样
System.out.println(cr.id + ":" + cr.name);
}
}
/*
* 泛型集合可以添加泛型的子类型的对象实例
*
* */
public void testChild(){
ChildCourse ccr = new ChildCourse();
ccr.id= "3";
ccr.name = "我是子对象的实例~~";
courses.add(ccr);
}
/*
* 泛型不能使用基本类型
*
* */
public void testBasicType(){
List<Integer> list=new ArrayList<Integer> ();
list.add(1);
System.out.println("基本类型必须使用包装类作为泛型!" + list.get(0));
}
public static void main(String[] atgs){
TestGeneric tg = new TestGeneric();
tg.testAdd();
tg.testForEach();
tg.testChild();
tg.testForEach();
tg.testBasicType();
}
}如果要是不用public以后便会报错 引用不到了 那后面的文件应该怎么改 才可以获取到前面那个封装了的id和name属性呢 自己试了很多遍 也看了封装那一节 还是不会改 求大牛帮忙指点一下 谢谢

使用ccr.getId();获得 id 值,使用ccr.getName();获得 name 值
Java入门第三季
409776 学习 · 4546 问题
相似问题
回答 3
回答 1