java - Polymorphism and inheritance -


in situation this:

class a{    public int x = 4;    public void s3(){       x = 3;    }    public void f(){       x = 8;       s3();    } }  class b extends a{    public int x = 5;    public void f(){       x = 10;       s3();    } }  a = new b(); b b = (b) a; a.f(); system.out.println(b.x); system.out.println(a.x); 

a.f() calls f() of class b, f(), after assignment, calls s3() function. @ point, s3() defined in a , when assigns value 3 x, x copy of variable owned class a. why s3() doesn't use x declared in b? in theory, b shouldn't has own copy of s3() function inherited a? (so s3() inherited a in b should use x declared in b)

you have misunderstanding of should doing in inheritance. extends reserved word wisely chosen. point of b extending b subset of additional attributes. you're not supposed redefine x in b; should handling x. redefining x in subclass, you're hiding superclass' field x (this true if x refers different variable types).

a = new b(); system.out.println(a.x);  //4 makes sense, since of class b b = (b) a; system.out.println(b.x);  //5 makes sense, since of class b a.f(); system.out.println(a.x);  //3 makes sense, since a.f() calls s3(), sets a's x 3 system.out.println(b.x);  //10  

the 10 follows printing b's x, assigned 10 call of a.f(), calls s3() why 3rd example prints 3. see mean @ this:

  public void f()    {       x = 10; //sets b's x 10       s3();  //calls a's s3(), sets a's x 3.    } 

Comments

Popular posts from this blog

python - How to create a legend for 3D bar in matplotlib? -

java - Multi-Label Document Classification -

php - Dynamic url re-writing using htaccess -