Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Treat object as another object

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();

1 Answers

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();
}
like image 67
Eran Avatar answered Apr 08 '26 09:04

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!