Java Reference
In-Depth Information
20
return
"Student"
;
21 }
22 }
23
24
class
Person
extends
Object {
25 @Override
26
override
toString()
public
String toString() {
27
return
"Person"
;
28 }
29 }
Student
Student
Person
java.lang.Object@130c19b
Method
m
(line 9) takes a parameter of the
Object
type. You can invoke
m
with any object
(e.g.,
new GraduateStudent()
,
new Student()
,
new Person()
, and
new Object()
)
in lines 3-6).
When the method
m(Object x)
is executed, the argument
x
's
toString
method is
invoked.
x
may be an instance of
GraduateStudent
,
Student
,
Person
, or
Object
. The
classes
GraduateStudent
,
Student
,
Person
, and
Object
have their own implementations
of the
toString
method. Which implementation is used will be determined by
x
's actual type
at runtime. Invoking
m(new GraduateStudent())
(line 3) causes the
toString
method
defined in the
Student
class to be invoked.
Invoking
m(new Student())
(line 4) causes the
toString
method defined in the
Stu-
dent
class to be invoked; invoking
m(new Person())
(line 5) causes the
toString
method
defined in the
Person
class to be invoked; and invoking
m(new Object())
(line 6) causes
the
toString
method defined in the
Object
class to be invoked.
Matching a method signature and binding a method implementation are two separate
issues. The
declared type
of the reference variable decides which method to match at com-
pile time. The compiler finds a matching method according to the parameter type, number of
parameters, and order of the parameters at compile time. A method may be implemented in
several classes along the inheritance chain. The JVM dynamically binds the implementation
of the method at runtime, decided by the actual type of the variable.
matching vs. binding
11.17
✓
✓
What is polymorphism? What is dynamic binding?
Check
11.18
Describe the difference between method matching and method binding.
Point
11.19
Can you assign
new int[50]
,
new Integer[50]
,
new String[50]
, or
new
Object[50]
, into a variable of
Object[]
type?
11.20
What is wrong in the following code?
1
public class
Test {
2
public static void
main(String[] args) {
3 Integer[] list1 = {
12, 24, 55, 1
};
4 Double[] list2 = {
12.4, 24.0, 55.2, 1.0
};
5
int
[] list3 = {
1, 2, 3
};
6 printArray(list1);
7 printArray(list2);
8 printArray(list3);
9 }
10
11
public static void
printArray(Object[] list) {
12
for
(Object o: list)
Search WWH ::
Custom Search