+ 1

Java Inheritance

package com.doubts; class X{ int a=10; } class Y extends X{ int a=20; } public class SL1 { public static void main(String[] args) { X x = new Y(); System.out.println(x.a); } } // Why output is not 20

25th Aug 2022, 2:03 AM
Mohd Aadil
Mohd Aadil - avatar
4 odpowiedzi
+ 1
class X{ int a=10; } class Y extends X{ int a=20; int super_a() { return super.a; } } public class SL1 { public static void main(String[] args) { Y y = new Y(); y.a = 200; // y has a 200 System.out.println( y.a); // but super a 10 stil exist as hidden System.out.println( y.super_a() ); System.out.println(); X x = y; // now y was reduced to his super type System.out.println( x.a); //10 // and y extensions cannot be accesed // error: // System.out.println( x.super_a() ); System.out.println(); Y y2 = (Y) x; // now y is back and his extensions too System.out.println( y2.a); //200 System.out.println( y2.super_a() ); } }
25th Aug 2022, 7:33 PM
zemiak
0
X x = .. x is of type X and value in X is 10 but you can cast it System.out.println( ((Y) x).a);
25th Aug 2022, 4:31 AM
zemiak
0
Class X is not abstract, inheritance does not work
25th Aug 2022, 12:29 PM
Cédric De Craim
Cédric De Craim - avatar
0
I appreciate your attention but still I'm confused can you please elaborate it bit more
25th Aug 2022, 2:51 PM
Mohd Aadil
Mohd Aadil - avatar