void sound(Animal animal) { if (animal instanceof Dog) { Dog dog = (Dog)animal(); dog.bark(); } if (animal instanceof Cat) { Cat cat = (Cat)animal(); cat.meow(); } }
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()); }
Animal a = new Dog(); if (a instanceof Dog){ Dog d = (Dog) a; d.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()
try { Dog d = new Dog(); } catch(Exception ex) { // treat exception } d.bark();
Dog d = null; try { d = new Dog(); } catch(Exception ex) { // treat exception } if(d != null) d.bark();
1. Animal a = new Dog(); 2. if (a instanceof Dog){ 3. Dog imADog = ( Dog ) a; 4. imADog.bark(); 5. }
Dog dog = new Dog(); dog.bark(); // Works as it is a dog Animal dogAsAnimal = (Animal) dog; dogAsAnimal.bark(); // Does not compile, dogAsAnimal is restricted to Animal though it is a Dog
Dog d = new Animal(); // not ok. d.bark(); // Animal doesn't have a bark();
Dog d = new Dog(); d.bark(); // Other animals don't bark, so we need to have the Dog here
@Test public void testAllBeanDiscovery(Dog dog) { ClassicInterceptor.reset(); dog.bark(); assertEquals(1, ClassicInterceptor.called); }
Dog speedy = new Dog(); speedy.eat(); speedy.sleep(); speedy.bark();
{ Dog lassie = new Dog(); Duck donald = new Duck(); lassie.eat(); lassie.sleep(); lassie.bark(); donald.eat(); donald.sleep(); donald.quack(); List<Animal> barn = new ArrayList<Animal>(); barn.Add(lassie); barn.Add(donald); }
public Animal createAnimal(){ Dog dog = new Dog(); dog.bark(); dog.bite(); dog.houl(); return dog; }
class TestDog { public static void main (String [] args){ Dog rex = new Dog(); rex.setName("Rex"); rex.setBreed("poodle"); rex.setSize(1); //rex.toString(); System.out.println(rex); rex.bark(3); } }
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