I’m facing strange OOP behaviour (IMO) in android and maybe in Java in general…
I have an activity and inside of it I instantiate an object of CustomSimpleCursorAdapter which is a class extending SimpleCursorAdapter. In my custom class I have some member variables added.
When I create an object of that class I want to be able to access a member variable of newly created object. My OOP experience was telling me that the following should suffice:
ListAdapter listAdapter = new TrainingsListCursorAdapter(...);
listAdapter.currentWidth = 100;
NOTE: currentWith variable is declared public…
(Eclipse) didn’t want to compile, so I thought maybe a public setter setCurrentWidth()in the custom class would solve it. I declared a member variable private and my setter method public….
ListAdapter listAdapter = new TrainingsListCursorAdapter(...);
listAdapter.setCurrentWidth(100);
Eclipse wasn’t pleased either… I knew it was a long shot, but when you face strange behaviour, you start to behave strange too :)))
The correction that eclipse was intrusively offering and in the end works! is the following code:
((TrainingsListCursorAdapter) listAdapter).setOrientationWidth(100);
Could someone please explain me this syntax and need for such casting?!
…and what’s wrong with:
- instantiate an object
- access it public setters/getters or directly member variables
It’s not particularly strange at all. The variable
listAdapteris just of typeListAdapter. The compiler couldn’t care less what assignments have occurred on previous lines. If you try to access a member which isn’t known viaListAdapter, the compiler will correctly complain.A simpler fix than casting would be to declare the variable as being the type you need it to be in order to access your specific members:
or
So to answer your final point – there’s nothing wrong with instantiating an object and accessing public members. There is something wrong with trying to do so via a variable of a type which doesn’t know about those members.
To give a simpler example in common types, you can’t write:
because
length()is a method onObject, it’s only onString. When the compiler sees the expressiontext.length(), it looks at the declared type of the variabletext(i.e.Objectin this case) and looks for thelength()method on that type.So this is what you’d do instead to make the above code work: