Reputation: 57
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
Upvotes: 1
Views: 2301
Reputation: 1584
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.
Upvotes: 0
Reputation: 159754
Unlike setID
, A
doesnt have a setName
method so there's no polymorphism for that method.
Upvotes: 2
Reputation: 33
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
}
}
Upvotes: 0
Reputation: 997
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");
}
}
Upvotes: 0
Reputation: 700
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
Upvotes: 0