forked from tugul/CoreJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMethodOverride.java
More file actions
77 lines (65 loc) · 2.38 KB
/
Copy pathMethodOverride.java
File metadata and controls
77 lines (65 loc) · 2.38 KB
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
72
73
74
75
76
77
package methods;
/**
* Method overriding rule
* - Overriding method must have same signature as method in parent class
* - Overriding method must be same or more accessible than method in parent class
* - Overriding method must not throw new or broader checked exception than exceptions thrown in parent method
* - If method returns a object, it must be same or subclass of that object's type returned in parent class
* - If method returns primitive, it must exactly match with primitive type returned in parent class
*
* For static method, it is called hiding method
* - Static method must remain static when overridden, same for non-static methods
*
* Calling Overridden method follows what object is called on
* Calling Hidden method follows what reference is called on
*
* For class fields, it same as static method, they are hidden
*
*/
class A {
static void staticMethod() {
System.out.println("Static method in A");
}
void instanceMethod(){
System.out.println("Instance method in A");
}
private int getIntValue() {
return 0;
}
void anotherInstanceMethod(){ staticMethod();}
}
class B extends A {
// It is hiding parent method
static void staticMethod(){
System.out.println("Static method in B");
}
// It is overriding
void instanceMethod() {
System.out.println("Instance method in B");
}
void anotherInstanceMethod() {
staticMethod();
}
// It is overriding
int getIntValue(){
return 1;
}
}
public class MethodOverride {
public static void main(String[] args) {
A a = new B();
a.instanceMethod(); // Instance method in B
a.staticMethod(); // Static method in A
new B().instanceMethod(); // Instance method in B
new B().staticMethod(); // Static method in B
System.out.println(new B().getIntValue()); // 1
new A().instanceMethod(); // Instance method in A
new A().staticMethod(); // Static method in A
//System.out.println(new A().getIntValue()); // DOES NOT COMPILE, inaccessible as it is private
System.out.println();
A ab = new B();
ab.anotherInstanceMethod(); // Static method in B
A aa = new A();
aa.anotherInstanceMethod(); // Static method in A
}
}