经常能看到通过父类引用去访问子类对象,但是不能访问子类对象特有的属性和方法。那么为什么这么写?为了程序的扩展性?可否能写的详尽些,真的很难理解,每次都卡在这里。。eg:
Collection c = new ArrayList();Collection为ArrayList父类。期待您点破。

解决方案 »

  1.   

    如果你在代码中显式创建一个对象,大可没必要写成:
    Collection list = new ArrayList();
    直接写成
    ArrayList list = new ArrayList();
    就OK了。但是如果你得到的对象的具体类型不知道(比如你不知道得到的是ArrayList还是LinkedList),就需要写成:
    List list = getMyList();  
      

  2.   

    为了oo思想最重要特点之一的多态
    以后不想用List而用Set的话可以直接换,而不影响处理c的代码
    如果要想处理子类的特定属性或方法,就向下转型
      

  3.   

    用父类的引用指向子类的对象这么做一般是为了利用多态来实现程序的可扩展性;
    但是子类的特有属性和方法千变万化,父类不可能是考虑到会有些什么
    故也就没必要提前留个什么接口。也没必要能引用到;况且想引用还不能。public class TestEat{
    public static void main(String[] args) {
    Animal a1 = new Tiger(2,"jack");
    Animal a2 = new Sheep(2,"herry");
    testMethod(a1);
    testMethod(a2);
    }
    public static void testMethod(Animal ani){
    ani.eat();
    }
    }
    abstract class Animal {
    public int age;
    public String name;
    public Animal(int age, String name){
    this.age = age;
    this.name = name;
    }
    public Animal(){

    }
    public abstract void eat();
    }class Tiger extends Animal{ public Tiger(int age, String name) {
    // TODO Auto-generated constructor stub
    super(age, name);
    }
    @Override
    public void eat() {
    System.out.println(this.name + "张开血盆大口的吃羊");
    }

    }
    class Sheep extends Animal{

    public Sheep(int age, String name) {
    // TODO Auto-generated constructor stub
    super(age, name);
    }

    @Override
    public void eat() {
    System.out.println(this.name + "细细的吃草");
    }
    }