java - classCastException please help me with real concept -


when object of subclass assigned variable of super class,why members accessible defined superclass

class {      int i=10;     void adsip() {         system.out.println(i);     } }  class b extends {     int j=20;     void bdsip() {          system.out.println(i+j);     }  }  class inherit4 {      public static void main(string[] x) {          a=new a();         b b=new b();         system.out.println("b.i="+b.i+"b.j="+b.j);         b.adsip();         b.bdsip();         a=b;         system.out.println("a.i="+a.i);         a.adsip();     } } 

above code working fine after adding a.j , a.bdisp(); error generated,as far know & b in above code represent refrence memory allocation of objects of class & b why code not able access a.j , a.bdsip(); in above code.

why members accessible defined superclass

because, @ runtime, superclass reference may pointing superclass instance or instance of class in subclass hierarchy.

superclass has method m1, subclass has method m1 , m2. want access m2 using reference of superclass. if, @ runtime, reference pointing instance of superclass (which not have m2) ?

so end result - @ runtime, members guaranteed accessible using superclass reference ones defined in superclass.


Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -