Reputation:
First I would like to say this is a cosmetic only question, as you will understand right away. I got an object, and I want that from now on, until I redecalre it, java will treat that object as another object, instead of me casting it again and again. For example, I got something like this:
Object obj = new SomeObject();
((SomeObject) obj).someMethod1();
((SomeObject) obj).someMethod2();
((SomeObject) obj).someMethod3();
Instead, I would like to do something like:
Object obj = new SomeObject();
obj treatas SomeObject; // This is the line that I dont even know if exist in java
obj.someMethod1();
obj.someMethod2();
obj.someMethod3();
Upvotes: 3
Views: 527
Reputation: 393781
You have to create a new variable (or declare obj
to be of SomeObject
type in the first place):
Object obj = new SomeObject();
SomeObject sobj = (SomeObject) obj;
sobj.someMethod1();
sobj.someMethod2();
sobj.someMethod3();
And in the more general case, if you don't know for sure that obj
is an instance of SomeObject
:
if (obj instanceof SomeObject) {
SomeObject sobj = (SomeObject) obj;
sobj.someMethod1();
sobj.someMethod2();
sobj.someMethod3();
}
Upvotes: 5