forked from rahulXbarnwal/JavaTutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMethodHiding.java
More file actions
54 lines (42 loc) · 1.27 KB
/
MethodHiding.java
File metadata and controls
54 lines (42 loc) · 1.27 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
package oops2;
// static variables and methods get inherited,
// but they do not behave like normal overridden methods
// static variables is accessible in child
class Parent {
static int x = 20;
static void staticMethod() {
System.out.println("Parent static");
}
void instanceMethod() {
System.out.println("Parent instance");
}
}
// static methods are accessible in child
class Child extends Parent {
}
// static methods can't be overridden
// since overriding is run time polymorphism
// static methods belongs to class , not object
// static binding happens at compile time
class Child2 extends Parent {
static void staticMethod() {
System.out.println("Child2 static");
}
@Override
void instanceMethod() {
System.out.println("Child2 instance");
}
}
public class MethodHiding {
public static void main(String[] args) {
System.out.println(Child.x); // 20
Child.staticMethod(); // Parent static
Parent p = new Child2();
p.staticMethod(); // Parent static
p.instanceMethod(); // Child2 instance
// because static methods are resolved using ref type, not object type
// Ref type = parent
// so Parent.show()
// this is method hiding
}
}