-8

How to call? How to do?

public class Test {
        public static void main(String[] args) {
            Test test = new Test();
            Animal a = new Animal("Animal");
            Dog d = new Dog(" BigDog ","yellow");
            Cat c = new Cat(" SmallCat ","black");
            test.f(a); test.f(d); test.f(c); //(1)
        }

        public void f(Animal a) {
            System.out.println("name :"+ a.name);

            if(a instanceof Dog) {
                Dog dog = (Dog)a;
                System.out.println("    "+ fursColor + "fur"); //!(2)!Error
            }
            else if(a instanceof Cat) {
                Cat cat = (Cat)a;
                System.out.println("  " + eyesColor + "eye"); //(3)!Error
            }
        }
    }

Ask Question:

(1) What's the meaning of this?

(2) How to call "yellow"?

(3) How to call "black"?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
aca
  • 25
  • 3
  • 8
    Is it a homework? – Petar Minchev Dec 03 '12 at 09:15
  • This is OOP theory, not an actual programming problem. Please read this [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html). Or you can read about Inheritance somewhere else – andreih Dec 03 '12 at 09:27

2 Answers2

0

For 1_

What you have here is subtype polymorphism. Youu are passing in sub-classes of Animal

For 2_ and 3_

You will need to pass something in to his method. You can pass in an object. For example

System.out.println(dog.getColour());

This assumes you have a getColour method in your object. You do not supply your definition of Animal so I can only assume this

RNJ
  • 15,272
  • 18
  • 86
  • 131
0

(1) What's the meaning of this?

The method f is using instanceof as it is not use polymorphic methods to select the right type.

Can you be more specific as to what you don't understand.

(2) How to call "yellow"?

I assume you want is to retrieve the String in the field in dog with dog.fieldNameNotShownInYourExample as it did in a.name to get the name.

(3) How to call "balck "?

I assume it should be "black" but its the same as 2)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130