Treat an object like another object

First I would like to say that this is a cosmetic issue, as you will immediately understand. I have an object, and I want that from now until I update it, java will treat this object as another object, instead of having to repeat it over and over 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();

      

+3


source to share


1 answer


You need to create a new variable (or declare obj

as a type SomeObject

):

Object obj = new SomeObject();
SomeObject sobj = (SomeObject) obj;
sobj.someMethod1();
sobj.someMethod2();
sobj.someMethod3();

      



And more generally, if you don't know exactly what obj

the instance is SomeObject

:

if (obj instanceof SomeObject) {
    SomeObject sobj = (SomeObject) obj;
    sobj.someMethod1();
    sobj.someMethod2();
    sobj.someMethod3();
}

      

+4


source







All Articles