void sound(Animal animal) { if (animal instanceof Dog) { Dog dog = (Dog)animal(); dog.bark(); } if (animal instanceof Cat) { Cat cat = (Cat)animal(); cat.meow(); } }
@InterceptorBindingAnnotation public class Dog implements DogInterface { @Override public void bark() { /* Silence */ } public void methodToBeDecorated() { } }
@Test public void testAnnotatedBeanDiscovery(Plant plant, Tree tree) { ClassicDecorator.reset(); plant.methodToBeDecorated(); assertEquals(1, ClassicDecorator.called); tree.methodToBeDecorated(); assertEquals(1, ClassicDecorator.called); }
public void methodToBeDecorated() { called++; delegate.methodToBeDecorated(); }
if (animal instanceof Cat) { Cat cat = (Cat) animal; cat.meow(); } else if (animal instanceof Dog) { Dog dog = (Dog) animal; dog.bark(); }
@InterceptorBindingAnnotation public class Stone { public void fall() { } }
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(); }
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()
Animal a; a = new Dog(); // "a" contains a Dog in memory, but we only KNOW that it's an Animal // because that is its declared type a.bark(); // fails at compile time - not all Animals can bark Dog d = (Dog) a; // This is a valid cast, because Dog extends Animal, but it's potentially unsafe. // // Another "valid" cast is: // Cat c = (Cat) a // but this would fail at runtime (ClassCastException) because the actual // object in memory (a Dog) cannot be cast to a Cat. if (a instanceof Dog) { // Now we KNOW that it's a Dog and we can cast safely. Dog d2 = (Dog) a; d2.bark(); // this is valid because d2's declared type is Dog }