Unsafe method of the same instance but of a different class
I have something like below:
Item var;
Depending on user input, it will be initialized as a different class:
if (/*user input*/ == 1) {
var = new Item();
} else {
var = new Truck();
}
Classes are defined as:
public class Truck extends Item {
public void someMethod();
public void exclusiveMethod();
}
public class Item {
public void someMethod();
}
Note Truck
has an exclusive method exclusiveMethod()
that Item
does not. Depending on certain conditions, var
a series of methods is called:
// will only return true if var was initialized as Truck
if (/*conditions*/) {
var.someMethod();
var.exclusiveMethod();
} else {
var.someMethod();
}
Netbeans throws an error message that exclusiveMethod()
cannot be found because it is not in Item
. I only need the method exclusiveMethod()
to be visible when it var
was initialized as Truck
. I have some limitations though: Item var;
must be in my code before other logic and I cannot create an interface that I then implement in Item
both Truck
. I also cannot change public class Item{}
at all.
What can I do?
source to share
You can use reflection APIs to call exclusiveMethod
.
The code will look something like this:
Method m = var.getClass().getMethod("exclusiveMethod", null);
if(m != null) {
m.invoke(var, null);
}
You can get more information on the debugging APIs here - http://docs.oracle.com/javase/tutorial/reflect/index.html
Another way to get this is by typing var
a Truck
if you're sure var is an object of type Truck
. example code for this would be -
if(var instanceof Truck) {
((Truck)var).exclusiveMethod()
}
source to share
As I understand it, if user input is 1 then it var
will be created as Truck
otherwise it should be created as Item
. The code is functional. I feel like you have a problem when calling the method exclusiveMethod()
, you can check the instance with instanceof
and then call the method like below:
if (var instanceof Truck) {
var.someMethod();
((Truck)var).exclusiveMethod();
} else {
var.someMethod();
}
source to share
This is the main polymorphism of OOP. Define an empty exclusiveMethod () function in your superclass (Item) and then override it in Truck by adding some code. You don't need any instructions or class checks.
public class Item {
public void someMethod() {
// do something
}
public void exclusiveMethod() {
}
}
public class Truck extends Item {
@Override
public void someMethod() {
// do something else
}
@Override
public void exclusiveMethod() {
// implement me
}
}
...
Item item = getItemOrTruck(...);
item.someMethod();
item.exclusiveMethod();
source to share