Object类 是所有类的父类
基类的引用可以指向所有子类
例如:Object o = new String();
自己创建的MyArrayList
Person p = (Person)L1.get(0);
向下转型:不安全
get()方法返回值为Object类型,需转换为Persen类型
class Person{
public void Print(){
System.out.println("我是一个好人");
}
}
class MyArrayList
{
Object[] array;
int capacity; // 空间的总大小
int size; // 空间中存储有效元素的个数
public MyArrayList(int capacity){
array = new Object[capacity];
size = 0;
this.capacity = capacity;
}
void add(Object e)
{
// 检测容量
array[size++] = e;
}
int size()
{
return size;
}
Object get(int index)
{
// 检测index不能越界
return array[index];
}
boolean isEmpty()
{
return 0 == size;
}
}
public static void main(String[] args) {
MyArrayList L1 = new MyArrayList(10);
L1.add(new Person());
L1.add(new Person());
L1.add(new Person());
// 向下转型:不安全
//
Person p = (Person)L1.get(0);
p.Print();
}
使用泛型的MyArrayList
class Person{
public void Print(){
System.out.println("我是一个好人");
}
}
// 泛型类
class Book{}
class Person{
public void Print(){
System.out.println("我是一个好人");
}
}
class MyArrayList<E>
{
public MyArrayList(int capacity){
array = (E[])new Object[capacity];
size = 0;
this.capacity = capacity;
}
public void add(E e)
{
// 检测容量
array[size++] = e;
}
public int size()
{
return size;
}
E get(int index)
{
// 检测index不能越界
return array[index];
}
boolean isEmpty()
{
return 0 == size;
}
E[] array;
int capacity; // 空间的总大小
int size; // 空间中存储有效元素的个数
}
public static void main(String[] args) {
// L1中只能存储Person类型的对象
MyArrayList<Person> L1 = new MyArrayList<>(10);
L1.add(new Person());
L1.add(new Person());
// L1.add(new Book()); 在编译阶段,发现类型不匹配,编译器报错
Person p = L1.get(0);
// Book b = (Book)L1.get(0); // 在编译阶段,发现类型不匹配,强转也不行
// L2中只能存储Book类型的对象
MyArrayList<Book> L2 = new MyArrayList<>(10);
L2.add(new Book());
}