Bonjour,
J'ai une question stupide sur l'héritage et le polymorphisme. ça fait un bon moment que je fais du java mais là j'avoue que je ne comprends pas bien...

Voici un petit code :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
 
package test ;
 
public class SurchargeTest {
 
	public static void main(String[] args) {
		new SurchargeTest().launchTest();
	}
 
	public void launchTest() {
		A a[] = new A[2];
		a[0] = new A1(5);
		a[1] = new A2(6);
 
		B b = new B1();
 
System.out.println(b.transform(a[0], " test "));
System.out.println(b.transform((A1) a[0], " test "));
System.out.println(b.transform(a[1], " test "));
 
}
 
	abstract class A {
		int value;
 
		A(int initValue) {
			value = initValue;
		}
 
		public String toString() {
			return "" + value;
		}
	}
 
	class A1 extends A {
		A1(int initValue) {
			super(initValue);
		}
	}
 
	class A2 extends A {
		A2(int initValue) {
			super(initValue);
		}
	}
 
	// class A3 A4 ...
 
	abstract class B {
		public abstract String transform(A a, Object c);
 
		public String transform(A1 a, Object c) {
			return "Cas special pour A1";
		}
	}
 
	class B1 extends B {
		public String transform(A a, Object c) {
			return "T1 " + a.toString() + c.toString();
		}
	}
 
	class B2 extends B {
		public String transform(A a, Object c) {
			return "T2 " + c.toString() + a.toString();
		}
	}
 
	// class B3, B4 ...
 
}
Et voici ce qui apparaît à l'écran lors de son exécution :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
 
T1 5 test 
Cas special pour A1
T1 6 test
Ma question est simple, pourquoi lors du premier appel "b.transform(a[0], " test ")", le retour n'est pas "Cas spécial pour A1" comme pour l'appel b.transform((A1)a[0], " test ").