KaiquanMah commited on
Commit
6f45b9a
·
verified ·
1 Parent(s): 121cf62

int approximation = (int) height;

Browse files
Week 6: Methods of OO Programming/11A. TYPE Conversions/CASTING+++ ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ As the type of a variable affects which features of an object can be referenced through it,
2
+ it's necessary to be able to change the type of the reference.
3
+ This is done through EXPLICIT TYPE CASTING.
4
+ We have previously used type casting, for example, when converting floating point numbers to integers:
5
+
6
+ double height = 175.25;
7
+ int approximation = (int) height;
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+ As previously noted, when class "Student" inherits from class "Person", a "Person"-type variable can be assigned a reference to a "Student" object.
16
+ However, this restricts the operations that can be used to those defined in the "Person" class.
17
+ Since the object is of type "Student", we can perform a type casting if necessary.
18
+
19
+ After the type casting, the properties defined in the "Student" class are available:
20
+
21
+ Person person = new Student("Oliver Student", "[email protected]", 14);
22
+
23
+ // Through the variable 'person', we cannot now request study credits,
24
+ // as the class has not defined the method.
25
+ // So let's do
26
+ // 'type casting'
27
+ // FROM 'Person' class to 'Student' class
28
+ Student oliver = (Student) person;
29
+
30
+ // approach 1 - BEST (less confusing)
31
+ System.out.println("Oliver's study credits: " + oliver.getStudyCredits());
32
+
33
+ // approach 2
34
+ // this also works, but it's starting to be quite a confusing line
35
+ System.out.println("Oliver's study credits: " + ((Student) person).getStudyCredits());
36
+
37
+
38
+
39
+
40
+
41
+
42
+ If we have an object created from the "Student" class and a "Student"-type variable,
43
+ and we want to refer to the object with a "Person"-type variable, no type casting is needed.
44
+ This is because all students are people, but only some people are students:
45
+
46
+ Student oliver = new Student("Oliver", "12354", 123);
47
+
48
+ // This is OK WITHOUT TYPE CASTING, because all
49
+ // Students are Persons
50
+ Person oliverAsPerson = oliver;
51
+
52
+ // This is also the same reason
53
+ Object oliverAsObject = oliver;
54
+
55
+ // VS
56
+ // The other way around requires conversion
57
+ Student oliver2 = (Student) oliverAsPerson;
58
+ Person oliverAsPerson2 = (Person) oliverAsObject;
59
+
60
+