Reputation: 112
If i put object of A class as argument of someMeth(Object o)
, how can i access to this object methods? I cant change or overrdie someMeth(Object o)
.
...
void someMeth(Object o) {
o.setS("example"); -- exception : setS() is undefined for type Object
}
...
class A {
private String s;
String getS () {
return s;
}
void setS(String value) {
s = value;
}
}
...
someMeth(new A());
Upvotes: 2
Views: 490
Reputation: 665
Try to convert type of reference:
void someMeth(Object o) {
if (o instanceof A) {
((A) o).setS("example");
}
}
Upvotes: 2
Reputation: 307
Try casting the object o
to they type A
like so:
A newObj = (A) o;
Then you can do:
newObj.setS("example");
Or a shorter, one line version:
((A)o).setS("example");
Upvotes: 2