+ 3

final method in java

I have read that private methods of superclass are considered to be final methods and can't be overriden but I am able to override one.How? class A { private void show() { System.out.println("class A"); } } class B extends A { void show() { System.out.println("class B"); } } class test { public static void main(String[] args) { B obj=new B(); obj.show(); } } OUTPUT: class B

14th Jun 2018, 3:37 PM
harshit
harshit - avatar
5 ответов
+ 4
becoz static method cant be overriden.. its is called function hiding
14th Jun 2018, 6:53 PM
Arun Tomar
Arun Tomar - avatar
+ 2
harshit this is not a function overriding. what you do is just static binding. as you know . you already bind the object with its functionality at compile time.. at function overriding... binding of object is always at run time. it means jvm take decision which one it run.. if you change A obj=new B(); than you see the error try to run this code making your function private and not private class B extends A { public static void main(String[] args) { A obj=new B(); obj.show(); } } class A { void show() { System.out.println("class A"); } }
14th Jun 2018, 5:06 PM
Arun Tomar
Arun Tomar - avatar
+ 1
ok thanks,but I have encountered a new problem.When I have made the method static the output is not "class B" instead it's "class A".Why? class A { static void show() { System.out.println("class A"); } } class B extends A { static void show() { System.out.println("class B"); } } public class test { public static void main(String[] args) { A obj=new B(); obj.show(); } }
14th Jun 2018, 6:25 PM
harshit
harshit - avatar
0
thanks
14th Jun 2018, 8:46 PM
harshit
harshit - avatar