import java.util.*; public class Dogprint2 { public static void main(String[] args) { Dog doggy = new Dog(); doggy.setbreed("Alsation"); doggy.setsize(5); ArrayList<Dog> dog2 = new ArrayList<Dog>(); dog2.add(doggy); for (Dog d : dog2) { System.out.println(d.getsize()); System.out.println(d.getbreed()); if (d.getsize() == 5) { d.bark(); } } } }
void sound(Animal animal) { if (animal instanceof Dog) { Dog dog = (Dog)animal(); dog.bark(); } if (animal instanceof Cat) { Cat cat = (Cat)animal(); cat.meow(); } }
Animal a1 = new Animal(); // works Animal a2 = new Dog(); // works, Dog a subtype of animal Dog d1 = new Animal(); // does not work, Animal not a subtype of Dog a1 = a2; // works d1 = a1; // doesn't work // If Dog has a function "bark" and Animal has a function "breathe" a1.breathe(); // works d1.breathe(); // works d1.bark(); // works a1.bark(); // does not compile, Animal not always a Dog
@Test public void testAllBeanDiscovery(Cat cat, Dog dog) { ClassicDecorator.reset(); cat.methodToBeDecorated(); assertEquals(1, ClassicDecorator.called); dog.methodToBeDecorated(); assertEquals(1, ClassicDecorator.called); }
if (animal instanceof Cat) { Cat cat = (Cat) animal; cat.meow(); } else if (animal instanceof Dog) { Dog dog = (Dog) animal; dog.bark(); }
public class SomeClass { private Dog dog; public void bark() { dog.bark(); // this is reusing the functionality without extending } }
Mammal x = ...; if (x instanceof Dog) { Dog d = (Dog) x; d.bark(); } else if (x instanceof Cat) { Cat c = (Cat) x; c.meow(); } if (x != null) { x.lactate(); }
public dodog(Dog mydog) { System.out.println(mydog.bark()); }
Cat sprinkles = new Cat(); // this doesn't make sense Dog aDog = (Dog) sprinkles; aDog.bark(); // can't do this because sprinkles can't bark() // but this does Animal myCat = (Animal) sprinkles; myCat.eat(); // but it can eat()
Dog d = new Animal(); // not ok. d.bark(); // Animal doesn't have a bark();