It dawned on me! #3 | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 1

It dawned on me! #3

What do you know about virtual methods in Java? In fact, all non-static non-public (that is, protected, package, and public) methods in java are virtual. Let's see the first Example: public class A { int i = 7; int getI() {return i;} } public class B extends A{ int i = 77; int getI() {return i;} } A a = new B(); System.out.println(a.i);//1 System.out.println(a.getI());//2 1. The class fields are not inherited, so the class A has its own field i and the class B has its own field i. Polymorphism does not work for fields, so when we access a.i, we turn to class A, so 3 will be displayed. 2. When we call the a.getI() method, polymorphism works in this case, so we'll call the method from the class whose instance was created. Accordingly, we get output 5. Let's see another Example: public class C { static int i = 7; static int getI() {return i;} } public class D extends C{ static int i = 77; static int getI() {return i;} } C c = new D(); System.out.println(c.i);//3 System.out.println(c.getI());//4 Static fields and methods are not virtual, so both calls will display 7. You can see these clearly see these examples here:https://code.sololearn.com/cYyBdMgmX3dF/#java

2nd Feb 2018, 8:43 AM
Dmitriy Yurkin
Dmitriy Yurkin - avatar
1 Respuesta
0
Thanks, but some errors in text and commented text, near output and display words. "so 3 will be displayed" - there is no field with number 3, just 7 and 77 etc. https://code.sololearn.com/cKtKfvW274lL/?ref=app
5th Apr 2018, 10:23 AM
Victor IT
Victor IT - avatar