Animal a = new Dog(); if (a instanceof Dog){ Dog d = (Dog) a; d.bark(); }
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 Dog(); d.bark(); // Other animals don't bark, so we need to have the Dog here
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 }
public static void main(String...args) { Dog snoopy = new Dog("snoopy"); snoopy.bark(); Dog.bark = new AggressiveBarkingStrategy(); snoopy.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; }
Dog speedy = new Dog(); speedy.eat(); speedy.sleep(); speedy.bark();
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); } }
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(); } } } }
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