4 Design Patterns Video Tutorial
4 Design Patterns Video Tutorial
043
044 Animal[] animals = new Animal[4];
045 animals[0] = doggy;
046 animals[1] = kitty;
047
048 System.out.println("Doggy says: " +animals[0].getSound());
049 System.out.println("Kitty says: " +animals[1].getSound() + "\n");
050
051 // Sends Animal objects for processing in a method
052
053 speakAnimal(doggy);
054
055 // Polymorphism allows you to write methods that don't need to
056 // change if new subclasses are created.
057
058 // You can't reference methods, or fields that aren't in Animal
059 // if you do, you'll have to cast to the required object
060
061 ((Dog) doggy).digHole();
062
063 // You can't use non-static variables or methods in a static function
064
065 // System.out.println(justANum);
066
067 // sayHello();
068
069 // You can't call a private method even if you define it in
070 // the subclass
071
072 // fido.bePrivate();
073
074 // You can execute a private method by using another public
075 // method in the class
076
077 fido.accessPrivate();
078
079 // Creating a Giraffe from an abstract class
080
081 Giraffe giraffe = new Giraffe();
082
083 giraffe.setName("Frank");
084
085 System.out.println(giraffe.getName());
www.newthinktank.com/2012/08/design-patterns-video-tutorial/ 2/3
1/17/2021 Design Patterns Video Tutorial
086
087 }
088
089 // Any methods that are in a class and not tied to an object must
090 // be labeled static. Every object created by this class will
091 // share just one static method
092
093 public static void changeObjectName(Dog fido){
094
095 fido.setName("Marcus");
096
097 }
098
099 // Receives Animal objects and makes them speak
100
101 public static void speakAnimal(Animal randAnimal){
102
103 System.out.println("Animal says: " + randAnimal.getSound());
104
105 }
106
107 // This is a non-static method used to demonstrate that you can't
108 // call a non-static method inside a static method
109
110 public void sayHello(){
111
112 System.out.println("Hello");
113
114 }
115
116 }
www.newthinktank.com/2012/08/design-patterns-video-tutorial/ 3/3