假如有父类  f(){}  子类  s(){...}  现有父类数组a,想要a中的一个元素属于子类,该怎么做?

解决方案 »

  1.   

    也就是说子类s作为a中的一个元素,该   class f{
    ..........
            }
      class s{
      ....
    }
    class p{
        f a[]=new f(5);
        for(){...}
      /*现要求s作为a[5]或者其他只要是a中的一个元素输出;ps  我是初学者如果问题太白痴也不要喷的过分,当然也可以喷*、
      

  2.   

    for(int i =0; i < 5; i++){
          a[i] = new S();
    }
      

  3.   


    public class Parent{
     int[] a = {1,2,3,4,5};}public class Child extends Parent{
    private static int fromParent;
    public Child(){
    fromParent = super.a[3];
    }
    public static void main(String[] args){
    int b = fromParent;
     System.out.println(b);
    }
     
      

  4.   

    首先数组是f类型的
    f[] a = new f[5];让第一个元素是s类型的
    a[0] = new s();所以二楼给的是对的
      

  5.   

    我理解是没有问题的.
    可以直接放就行,其中做了向上转型.import java.util.Arrays;
    class F
    {
    String id=null; F()
    {
    id="999";
    }
    F(String id)
    {
    this.id=id;
    }
    void methodF()
    {
    System.out.println("in F");
    }
    public String toString()
    {
    return id;
    }
    }
    class Son extends F
    {
    Son()
    {
    }
    void methodSon()
    {
    System.out.println("in son");
    }
    }
    public class SonObjectInAnArrayOfFather
    {
    public static void main(String[] args)
    {
    F[] f=new F[5]; //定义F类的数组。
    f[0]=new F("1"); //f[0]--f[3]存放父类对象。
    f[1]=new F("2");
    f[2]=new F("3");
    f[3]=new F("4");
    Son s=new Son();
    s.methodSon();
    f[4]=s; //存放子类对象。(都向上转型了).
    f[3].methodF();
    f[4].methodF();
    //f[4].methodSon(); //编译错误。子类特有的东西都不可见了。 System.out.println("f[4] is an instance of Son? "+(f[4] instanceof Son));
    System.out.println("f[4] is an instance of F? "+(f[4] instanceof F));
    System.out.println(Arrays.toString(f)); //Object 是所有类的父类,你可以放任何子类对象.
    Object[] o=new Object[5];
    o[0]="abc"; //String对象。
    o[1]=new F("1");
    o[2]=new Thread(); //线程对象.
    o[3]=new Object(); //Object对象。
    o[4]=new Son();
    System.out.println(Arrays.toString(o));
    }
    }
      

  6.   

    你确定吗为什么这样用会出错呢  o[0]=new F()  
       o[0].xxx;
    同样报错  The method setPostCredit(float)【(F类方法)】 is undefined for the type Object
       
      

  7.   

    执行其实际类的方法,肯定会错,只能执行Object的方法。要想执行具体的类的方法,需要向下转型。