简体   繁体   中英

Array of different class objects in java

I am trying to create an array of different objects and call class methods for individual objects.

class A
{
    int ID,
    String name,
    public int getID()
    {
        return ID;
    }
    public void setID(int id
    {
        ID = id;
    }
}
class B extends A
{
    string name;
    public string getName()
    {
        return name;
    }
    public void setName(string n)
    { 
        name = n;
    }
}
class Implement
{
    public static void main(string[] args)
    {
        A[] a1 = new A[2];
        a1[0] = new B();
        a1[1] = new B();
        a1[0].setID(123);
        a1[0].setName("John"); //Error
    }
}

I am not able to access the B class method. Can any one help me understand why it is not allowing me to access and how to achieve this... Appreciate your help.. Thanks

setID不同, A没有setName方法,因此该方法没有多态性。

This is because the reference type of a[0] is of parent class A where the method setName is not defined. To be able to call setname you can cast a[0] to type B

Because the compiler thinks every item of your list "is a" A because you declared a1 as a list of A. You can only call methods that belong to A. Suppose the 3rd item of your list was of type A, then you'd never be able to call setName() on it. Now, if you are certain that the 1st item of your list is a B, you can cast it:

((B)a1[0]).setName("name");

If you really want to use polymorphism, you need setName() to be defined on the parent class (A). Then, all the children can redefine what setName() does.

There are several syntax errors in your code. Also, you are creating the array with type A and setName is in type B . Here is updated code:

class A
{
    int ID;
    String name;
    public int getID()
    {
        return ID;
    }
    public void setID(int id)
    {
        ID = id;
    }
}
class B extends A
{
    String name;
    public String getName()
    {
        return name;
    }
    public void setName(String n)
    { 
        name = n;
    }
}
class Implement
{
    public static void main(String[] args)
    {
        B[] a1 = new B[2];
        a1[0] = new B();
        a1[1] = new B();
        a1[0].setID(123);
        a1[0].setName("John");
    }
}

Copy your code instead of retyping it. There are a lot of typos in here. Use this:

class Implement
{
     public static void main(String[] args)
     {
        A[] a1 = new A[2];
        a1[0] = new B();
        a1[1] = new B();
        a1[0].setID(123);
        ((B)a1[0]).setName("John"); //No error
      }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM