1/17/2021 Design Patterns Video Tutorial
001 public class WorkWithAnimals{
002
003 int justANum = 10;
004
005 public static void main(String[] args){
006
007 Dog fido = new Dog();
008
009 [Link]("Fido");
010 [Link]([Link]());
011
012 [Link]();
013
014 [Link](-1);
015
016 // Everything is pass by value
017 // The original is not effected by changes in methods
018
019 int randNum = 10;
020 [Link](randNum);
021
022 [Link]("randNum after method call: " + randNum);
023
024 // Objects are passed by reference to the original object
025 // Changes in methods do effect the object
026
027 changeObjectName(fido);
028
029 [Link]("Dog name after method call: " + [Link]());
030
031 [Link]("Animal Sound: " + [Link]());
032
033 // Create a Dog and Cat object with the super class
034 // but the Dog and Cat reference type
035
036 Animal doggy = new Dog();
037 Animal kitty = new Cat();
038
039 [Link]("Doggy says: " + [Link]());
040 [Link]("Kitty says: " + [Link]() + "\n");
041
042 // Now you can make arrays of Animals and everything just works
[Link]/2012/08/design-patterns-video-tutorial/ 1/3
1/17/2021 Design Patterns Video Tutorial
043
044 Animal[] animals = new Animal[4];
045 animals[0] = doggy;
046 animals[1] = kitty;
047
048 [Link]("Doggy says: " +animals[0].getSound());
049 [Link]("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 // [Link](justANum);
066
067 // sayHello();
068
069 // You can't call a private method even if you define it in
070 // the subclass
071
072 // [Link]();
073
074 // You can execute a private method by using another public
075 // method in the class
076
077 [Link]();
078
079 // Creating a Giraffe from an abstract class
080
081 Giraffe giraffe = new Giraffe();
082
083 [Link]("Frank");
084
085 [Link]([Link]());
[Link]/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 [Link]("Marcus");
096
097 }
098
099 // Receives Animal objects and makes them speak
100
101 public static void speakAnimal(Animal randAnimal){
102
103 [Link]("Animal says: " + [Link]());
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 [Link]("Hello");
113
114 }
115
116 }
[Link]/2012/08/design-patterns-video-tutorial/ 3/3