Sorry for the crappy title I failed to think of a better version for my Java question. I am right now using Java version: 1.6.0_18 and Netbeans version: 6.8
Now for the question.
What I've done is created a class with only one protected int property and next I made a public method to Set the int property to a given value. Then I made an object of that class and used said public method to set the int property to 5. Now I need your help to create another class that will take said object and expose it's protected int property.
The way I could think of doing this was to create a sub class to inherit said class and then create a method to Get the int property of the super class. I kind of succeeded to create the code to Get the int property but now I can't figure out how to use this new sub class to reference the object of the super class.
Here are the 2 classes I have thus far:
public class A { protected int iNumber; public void setNumber ( int aNumber ) { iNumber = aNumber; } }
public class B extends A { public int getNumber() { return super.iNumber; } }
I created an object of 'A' and used its method to set its property to 5, like this:
A objA = new A(); objA.setNumber ( 5 );
Now I want to create an object of 'B' to output the int stored within the property of 'objA'. I've tried to run this code:
B objB = (B) objA; String aNumber_String = String.valueOf( objB.getNumber() ); System.out.println( aNumber_String );
but I got the error: "java.lang.ClassCastException" on the first line
B objB = (B) objA;
Please is there anyway of doing what I am trying to do?
P.S. I am hoping to make this idea work because I do not want to edit class A (unless I have no choice) by giving it a getter method.
P.P.S Also I know it's a 'bad' idea to expose the property instead of making it private and use public setter / getter methods but I like it this way :).
Edit: Added code tags