oop - Java - can I extend an instance of a class to make it a parent class instance? -


here small artificial example of trying achieve. have class many parameters - dog. have child class jumpydog , want learn how can can "extend" instance of dog make instance of jumpydog.

class dog {     int age, numberofteeth, grumpiness, manyotherparameters;     jumpydog learntojump(int height) {         jumpydog jumpy = new jumpydog(this); // not want copy parameters         jumpy.jumpheight=height;         return jumpy;     } }  class jumpydog extends dog {     int jumpheight;     void jump(){} } 

or can that:

dog dog=new dog(); dog.makejumpy(); dog.jump() 

you can implement decorator pattern in java avoid copying fields initial object during "extension" internally keeping reference it, won't dog anymore (because dog class has fields avoiding copy).

class jumpydog {     dog measdog;     int jumpheight;      public jumpydog(dog me) {         measdog = me;     }      public dog measdog() {         return measdog();     }      void jump(){} } 

you can use following:

dog dog=new dog(); jumpydog measjumpy = dog.learntojump(100); measjumpy.jump() 

and no, can not following example because dog hasn't jump() method:

dog dog=new dog(); dog.makejumpy(); dog.jump() // dog has no method jump 

Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

python - build a suggestions list using fuzzywuzzy -