package com.collection;
public class Book {
public String id;
public String name;
public void Book(String id,String name) {
this.id = id;
this.name = name;
}
}
package com.collection;
import java.util.ArrayList;
import java.util.List;
public class ListTest {
public List BookToSelect;
public ListTest(){
this.BookToSelect=new ArrayList();
}
public void BookAdd(){
Book bt=new Book("1.","《三国演义》");//此处编译器报错
BookToSelect.add(bt);
Book temp=(Book) BookToSelect.get(0);
System.out.println("添加了第一本书:"+bt.id+bt.name);
}
public static void main(Sring[] args){
ListTest lt=new ListTest();
lt.BookAdd();
}
}
如果把Book类中的属性设置为private,那么在Book中应该怎么去添加书呢?
public class ListTest {
public List BookToSelect;
public ListTest(){
this.BookToSelect=new ArrayList();
}
public void BookAdd(){
Book bt0=new Book("1.","《三国演义》");
BookToSelect.add(bt0);
Book temp0=(Book) BookToSelect.get(0);
System.out.println("添加了第一本书:"+temp0.getId()+temp0.getName());
Book bt1=new Book("2.","《水浒传》");
BookToSelect.add(0,bt1);
Book temp1 = (Book)BookToSelect.get(0);
System.out.println("添加第二本书:"+temp1.getId()+temp1.getName());
}
public static void main(Sring[] args){
ListTest lt=new ListTest();
lt.BookAdd();
}
}
跟老师一样敲的代码,怎么就运行不了呢?(包已经导了)
包已经导了啊 !
设置为私有与添加不冲突,Book的构造一样可以调用,知识没法通过对象+.的方式访问私有变量。
你注释了编译器报错的那一处是不是因为你没有导包?
第一个\n就是打印换行 就会这一个