I am learning Java and like to do it through examples. This is about inheritance and variables.
Animal.java
package inheritance;
public class Animal {
String name;
public Animal (){
System.out.println("A new animal has been created!");
}
public Animal (String name){
System.out.println(name + " has been created!");
}
public void sleep() {
System.out.println ("An animal sleeps...");
}
public void speak(){
System.out.println("An animal *speaks*");
}
public void eat() {
System.out.println ("An animal eats...");
}
}
Dog.java
package inheritance;
public class Dog extends Animal {
public Dog(){
super();
}
public Dog(String name){
super();
System.out.println(name + " has been created!");
}
public void sleep(){
System.out.println("A dog sleeps...");
}
public void speak(){
System.out.println("A dog *barks*");
}
public void speak(String name){
System.out.println(name + " *barks*");
}
public void eat() {
System.out.println("A dog eats...");
}
}
Zoo.java
package inheritance;
import java.util.ArrayList;
import java.util.List;
public class Zoo {
public static void main(String[] args)
{
Dog ruffruff = new Dog();
Dog Fido = new Dog("Fido");
System.out.println();
List<Animal> Animals = new ArrayList<Animal>();
Animals.add(ruffruff);
Animals.add(Fido);
for (Animal AnAnimal:Animals) //for each structure.
{
AnAnimal.speak();
AnAnimal.sleep();
}
Fido.speak("Fido");
}
}
Output:
A new animal has been created!
A new animal has been created!
Fido has been created!
A dog barks
A dog sleeps...
A dog barks
A dog sleeps...
Fido barks
Desired Output:
A new animal has been created!
Fido has been created!
A dog barks
A dog sleeps...
Fido barks
Fido sleeps...
Questions:
How can I name a dog ONCE. So I want to name Fido ONCE in this code. Also I know I can say: Fido.speak("Fido"); But that messes up the array. Also seems illogical.
Why Array?
I have several others Cow, Bird, etc. I want a generic print out and then a name set to the object when I desire a name to be added.
Thanks for reading and your time! :)
------------------------------After Patricia's tips-----------------------------
package inheritance;
public class Animal {
protected String name = "";
public Animal (){
System.out.println("A new animal is born!");
}
public Animal (String name){
this.name = name;
System.out.println("A " + name + " is born!");
}
public void sleep() {
if (name.isEmpty())
{
System.out.println("An animal sleeps...");
}
else
{
System.out.println ("A " + name + " sleeps...");
}
}
public void speak() {
if (name.isEmpty())
{
System.out.println("An animal speaks...");
}
else
{
System.out.println ("A " + name + " speaks...");
}
}
public void eat() {
if (name.isEmpty())
{
System.out.println("An animal eats...");
}
else
{
System.out.println ("A " + name + " eats...");
}
}
}
I would change one of your constructors:
to
so that the Animal has a name, and then use the name in the message.