My only issue here is i am not able to invoke line 41
owner.pets[ 3 ].getAction();?

Any ideas why?

Inline Code Example Here

abstract class Pet1 {
    abstract void perform();
}

class Dog extends Pet {
    void perform() { System.out.println("*The dog rolls over*"); }
}
class GoldFish extends Pet{
    void perform() { 
    System.out.println("*GoldFish eats alot*"); }
    public String action = "Blowing bubbles";
    GoldFish(){
    }
    GoldFish( String action ){
    this.action = action;
    }
    public String getAction(){
    return this.action;

    }   
}
class Human {

    String firstName = "Unknown";
    String lastName = "Unknown";
    Pet[] pets = new Pet[ 5 ]; 
    void speak() { System.out.println( "My name is " + firstName + " " + lastName ); }
}
class Example2 {
    public static void main( String[] args ) {
        Human owner = new Human();
        owner.firstName = "Andy";
        owner.lastName = "Cole";
        owner.speak();
        owner.pets[ 0 ] = new Dog();
        owner.pets[ 1 ] = new Fish();
        owner.pets[ 2 ] = new GoldFish();
        owner.pets[ 3 ] = new GoldFish("Hamster");
        owner.pets[ 4 ] = new GoldFish("Iguana");

        owner.pets[ 3 ].getAction(); 

        System.out.println("My pets will perform the following tricks:");
        if ( owner.pets != null ) {
            for ( int i = 0; i < owner.pets.length; i++ ) {
                Pet somePet = owner.pets[i];
                if ( somePet != null ) {
                    somePet.perform();
                }
            }
        }

    }
}

Edited 4 Years Ago by Valiantangel: correction

i am not able to invoke line 41
owner.pets[ 3 ].getAction();?

Do you get compiler errors? If so please post them.
Otherwise explain what the problem is.

Note: the getAction() method returns a String that your code ignores.

Ok below is the error message:

Example2.java:42: error: cannot find symbol
owner.pets[3].getAction();
^
symbol: method getAction()
location: class Pet
1 error

pets is an array of Pets, so pets[ 3 ].getAction() requires the getAction method to be defined for the class Pet, but it's not, it's only defined for GoldFish. I know that you know that pets[3] contains a GoldFish, but that's not something the compiler can figure out.

This article has been dead for over six months. Start a new discussion instead.