CoolFace
Apppublic

KaiquanMah/TurkuBasicOOPinJava

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
12A. Dynamic Binding+++253 linesDownload Raw Back to Week 6: Methods of OO Programming
1Let's also examine a situation where a METHOD is OVERRIDDEN in a subclass. 2In the class "Lorry", the method getCapacity has been IMPLEMENTED AGAIN:3 4class Truck {5    private int capacity;6    7    public Truck(int capacity) {8        this.capacity = capacity;9    }10    11    public int getCapacity() {12        return this.capacity;13    }14}15 16 17class Lorry extends Truck {18    private int trailerCapacity;19 20    public Lorry(int capacity, int trailerCapacity) {21        super(capacity);22        this.trailerCapacity = trailerCapacity;23    }24 25    // HERE26    @Override27    public int getCapacity() {28        return super.getCapacity() + trailerCapacity;29    }30}31 32 33 34 35 36 37Let's create a new object of type "Lorry", and save the reference to a "Truck"-type variable.38 39The type of the variable defines the operations that can be used: 40thus, we can only call methods defined in the "Truck" class. 41So let's call the "getCapacity" method, which is defined in the "Truck" class and overridden in the "Lorry" class.42 43public class LorryTest {44    public static void main(String[] args) {45        46        //INITIALISE 'Lorry' object as a 'Truck' / superclass47        Truck vehicle = new Lorry(10, 20);48        System.out.println("Capacity: " + vehicle.getCapacity());49    }50}51 52The program outputs53Capacity: 3054 55 56 57 58From this example, we notice that the method call is directed to the implementation given in the Lorry class, even though the type of the variable is Truck. 59As a general rule,60- The VARIABLE TYPE DETERMINES the AVAILABLE OPERATIONS / METHODS61- The OBJECT TYPE determines the IMPLEMENTATIONS used by the METHODS62 63This is called dynamic binding: Java always looks for the LATEST IMPLEMENTATION of each METHOD.64https://docs [dot] google [dot] com/presentation/d/e/2PACX-1vTpe_7VNECaErEVyCbdD2Ud_CcEaS7sDoG7YD5ic--v34mX0QCzEZRQ-q-ENqkjTI6wiGT-Kh0rHNPl/embed?start=false&amp;loop=false&slide=id.p65 66 67 68 69 70 71 72 73 74 75 76==========================================77 78 79Note that dynamic binding works in the same way also with internal calls of an object.80 81Let's look at a situation where the class 'DetectiveNovel' inherits from the class 'Book'. 82In the "DetectiveNovel" class, the 'getTitle' method is overridden, but not the toString method.83 84class Book{85    public String getTitle(){86        return "book - ";87    }88    89    public String getPublisher(){90        return "publisher";91    }92 93    public String toString(){     94        return getTitle() + getPublisher();95    }96}97 98 99class DetectiveNovel extends Book {100 101    @Override102    public String getTitle() {103        return "detective novel - ";104    }105}106 107 108 109 110When the "toString" method is called for a "DetectiveNovel"-type object, 111it always uses the "DetectiveNovel" class implementation for the "getTitle" method:112 113public class DetectiveNovelTest {114    public static void main(String[] args) {115        Book book = new DetectiveNovel();116        System.out.println(book.toString());117    }118}119 120 121// 'Book' toString()122// IMPLEMENTs getTitle() + getPublisher()123// ie 'DetectiveNovel'/OVERRIDDEN getTitle() + 'Book'/ORIGINAL getPublisher()124The program outputs:125detective novel - publisher126 127 128 129 130 131 132 133 134 135 136==========================================137 138 139 140 141 142 143 144 145 146 147 148Determining the Type of an Object149As the TYPE of an OBJECT DETERMINES the outcome of a METHOD CALL in some situations, 150we need to be able to determine the type. 151This is done, for instance, with the operator 'instanceof'. 152The operator returns the value true, if the given object is of the given class type, i.e.153 154 155A instanceof B156obj1 instanceof Class1157variable1 instanceof Class1158returns the value true if A's type is B.159 160 161 162 163An example clarifies the situation:164public static void main(String[] args) {165    Person ollie = new Student("Oliver", "12345", 123);166    System.out.println(ollie instanceof Student);167    System.out.println(ollie instanceof Person);168    System.out.println(ollie instanceof Object);169    System.out.println(ollie instanceof Teacher);170}171The Program outputs:172true173true174true175false176 177 178 179 180 181 182 183 184So, a "Student" type is both a "Student", "Person" and "Object". 185In fact, the statement186 187A instanceof Object188is true for all Java objects, as "Object" is the superclass of all classes.189 190 191 192 193 194 195 196 197 198If there is a need TO DETERMINE the "ACTUAL" TYPE of an OBJECT and the type of the superclass is not sufficient, 199we can use the method "getClass":200 201public static void main(String[] args) {202    Person oliver = new Student("Oliver", "12345", 123);203    204    System.out.println("Oliver is a Person: " + (oliver instanceof Person));205    System.out.println("Oliveris a Person: " + (oliver.getClass() == Person.class));206    207    System.out.println("Oliver is a Student: " + (oliver instanceof Student));208    System.out.println("Oliver is a Student: " + (oliver.getClass() == Student.class));209}210 211Ohjelma tulostaa:212Oliver is a Person: true // 'Student' object type is a subclass of 'Person'213Oliver is a Person: false // 'Student' object type was not initialised as a 'Person' class214Oliver is a Student: true // 'Student' object type215Oliver is a Student: true // 'Student' object type was initialised as a 'Student' class216 217 218 219====================220 221 222 223 224A typical example is the "equals" method, 225where it is determined whether an object is of the same type as the object being compared226- see an example by generating the "equals" method in Eclipse!227 228Let's consider an example of a method that receives a list of "Person"-class type objects 229and prints information about each object, 230whether it is a "Person", "Student" or "Teacher" object:231 232// VARIABLE TYPE = 'Person'233// OBJECT TYPE => depends on HOW OBJECTS WERE INITIALISED234public static void whatType(ArrayList<Person> people) {235    for (Person person : people) {236    237        if (person.getClass() == Person.class) {238            System.out.println("This is a person!");239        } 240        else if (person.getClass() == Student.class) {241            System.out.println("This is a student!");242        } 243        else if (person.getClass() == Teacher.class) {244            System.out.println("This is a teacher!");245        }246    }247}248 249 250 251 252 253