| Author |
Code won't compile !!
|
Mandeep Anttal
Greenhorn
Joined: Jan 13, 2010
Posts: 4
|
|
Hey everyone,
I am brand new to Java. So, kindly bear with me :p
I am following Head First java 2nd Edition and I am presently at the 8th chapter of the book (Interfaces and Polymorphism).
Following code (Page 207) is not compiling:
public class MyAnimalList {
private Animal [] animals = new Animal[5];
private int nextIndex = 0;
public void add(Animal a) {
if (nextIndex < animals.length) {
animals[nextIndex] = a;
System.out.println("Animal added at " + nextIndex);
nextIndex++;
}
}
}
Hence, as a result I am not able to run this test code:
public class AnimalTestDrive {
public static void main(String[] args) {
MyAnimalList list = new MyAnimalList();
Dog a = new Dog();
Cat c = new Cat();
list.add(a);
list.add(c);
}
}
The error message that I am getting while compiling the first piece of code is:
C:\Users\Deep\Desktop>javac MyAnimalList.java
MyAnimalList.java:3: cannot find symbol
symbol : class Animal
location: class MyAnimalList
private Animal [] animals = new Animal[5];
^
MyAnimalList.java:6: cannot find symbol
symbol : class Animal
location: class MyAnimalList
public void add(Animal a) {
^
MyAnimalList.java:3: cannot find symbol
symbol : class Animal
location: class MyAnimalList
private Animal [] animals = new Animal[5];
^
3 errors
What I suppose is going wrong is, maybe the compiler is not able to understand Animal because it is not sure about its type.
Am I supposed to declare a datatype for the animals array?
** Thanks **
|
 |
salvin francis
Ranch Hand
Joined: Jan 12, 2009
Posts: 915
|
|
use code tags to post code.
Have you written a class named "Animal" ?
if yes, where is it placed ? In the same directory ?
|
My Website: [Salvin.in] Cool your mind:[Salvin.in/painting] My Sally:[Salvin.in/sally]
|
 |
Mahender Parkipandla
Greenhorn
Joined: Dec 28, 2009
Posts: 3
|
|
I think you have to write an interface Animal and the classes Dog and Cat should implement that interface.
Please check it once.
|
 |
Mandeep Anttal
Greenhorn
Joined: Jan 13, 2010
Posts: 4
|
|
That was the problem. Completely forgot to compile the Animal class.
The code works now.
Thanks Mahender.
|
 |
Mandeep Anttal
Greenhorn
Joined: Jan 13, 2010
Posts: 4
|
|
Yes, that was the missing link Mahi.
Thanks.
|
 |
Mandeep Anttal
Greenhorn
Joined: Jan 13, 2010
Posts: 4
|
|
|
Thanks Salvin !
|
 |
salvin francis
Ranch Hand
Joined: Jan 12, 2009
Posts: 915
|
|
happy to help
|
 |
Mahender Parkipandla
Greenhorn
Joined: Dec 28, 2009
Posts: 3
|
|
|
You are welcome Mandeep
|
 |
 |
|
|
subject: Code won't compile !!
|
|
|