+ 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
4 Respostas
+ 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() );
}
}
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);
0
Class X is not abstract, inheritance does not work
0
I appreciate your attention but still I'm confused can you please elaborate it bit more