2

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());
1
  • this is just bad design Commented Apr 16, 2017 at 12:22

2 Answers 2

2

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");
Sign up to request clarification or add additional context in comments.

Comments

2

Try to convert type of reference:

void someMeth(Object o) {
     if (o instanceof A) {
         ((A) o).setS("example");
     }
}

2 Comments

but you can do that without determinating of o instantiates
If your intent is "call concrete method", you determine instance automatically in your mind. If you have several instances, you need to create interface with method setS() and convert o to your interface type. If you'll remove if statement and object won't instance of A you can catch ClassCastException.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.