java - Use a subclass object to modify a protected propety within its superclass object -


sorry crappy title failed think of better version java question. right using java version: 1.6.0_18 , netbeans version: 6.8

now question.

what i've done created class 1 protected int property , next made public method set int property given value. made object of class , used said public method set int property 5. need create class take said object , expose it's protected int property.

the way think of doing create sub class inherit said class , create method int property of super class. kind of succeeded create code int property can't figure out how use new sub class reference object of super class.

here 2 classes have far:

public class {   protected int inumber;    public void setnumber ( int anumber )   {     inumber = anumber;   } }
public class b extends {   public int getnumber()   {    return super.inumber;   } }

i created object of 'a' , used method set property 5, this:

 obja = new a(); obja.setnumber ( 5 ); 

now want create object of 'b' output int stored within property of 'obja'. i've tried run code:

 b objb = (b) obja; string anumber_string = string.valueof( objb.getnumber() ); system.out.println( anumber_string ); 

but got error: "java.lang.classcastexception" on first line

 b objb = (b) obja; 

please there anyway of doing trying do?

p.s. hoping make idea work because not want edit class (unless have no choice) giving getter method.

p.p.s know it's 'bad' idea expose property instead of making private , use public setter / getter methods way :).

edit: added code tags

for line

b objb = (b) obja; 

the object of class a not object of class b, cast not allowed.

the class relationship between a , b is, b is-a a, (because class b extends a), inverse cannot said in case.

take following example, following exists:

  • class animal.
  • class dog extends animal

what being attempted in above example cast animal dog:

dog dogobject = (dog)animalobject;  // not allowed. 

this cannot case, not animals dogs -- know, animalobject instance of class cat extends animal, not dog.


Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -