Undestanding Java Inheritance: strange behaviour -



Undestanding Java Inheritance: strange behaviour -

i don't understand unusual behavior of class inheritance.

this parent class:

public class cubetti implements token{ ... private int id=1; ... public cubetti(int n) { numero = n; } ... public int getid() { homecoming id; } public void setid( int idx) { id = idx; } ... }

and subclass:

public class rgc extends cubetti{ private int id=0; ... public rgc (int idx) { super(0); id = idx; // unusual behaviour ! } ... }

this test mainclass:

public static void main(string[] args) { rgc uno = new rgc(1); rgc due = new rgc(2); system.out.println(" uno id " + uno.getid() + " due id is" + due.getid()); }

the output

uno id 1 , due id 1

but if utilize in tagged line on rgc subclass:

.... // id = idx; setid(idx); ....

the output

uno id 1 , due id 2

why?

you have id variable in both cubetti super-class , rgc sub-class. using setter , getter updates/returns id of super-class, since methods defined in super-class , not overridden sub-class.

calling id = idx in sub-class constructor modifies sub-class's variable, since sub-class's variable hides super-class's variable, , if didn't hide it, wouldn't able access sub-class, since it's private.

java inheritance

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -