Method nonvisibility of same instanceof but differing class

77 views Asked by At

I have something like the 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();
}

The 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 have. Depending on some conditions, a series of methods will be called on var:

// will only return true if var was initialized as Truck
if (/*conditions*/) {
    var.someMethod();
    var.exclusiveMethod();
} else {
    var.someMethod();
}

Netbeans pops up an error that exclusiveMethod() cannot be found because it is not in Item. I need method visibility of exclusiveMethod() only when var was initialized as Truck. I have some constraints, though: Item var; must be in my code before other logic, and I cannot create an interface which I then implement in both Item and Truck. I also cannot modify public class Item{} at all.

What can I do?

3

There are 3 answers

2
Anand S Kumar On BEST ANSWER

You can use reflection APIs to call the exclusiveMethod .

The code would look something like -

Method m = var.getClass().getMethod("exclusiveMethod", null);
if(m != null) {
    m.invoke(var, null);
}

You can get more information about relfection APIs here - http://docs.oracle.com/javase/tutorial/reflect/index.html


Another way to get this is by casting the var onto a Truck , if you are sure that var is an object of type Truck . the example code for that would be -

if(var instanceof Truck) {
    ((Truck)var).exclusiveMethod()
}
0
Blip On

As from you question I understand that if the user input is say 1 then the var would be instantiated as Truck else it should be instantiated as Item. The code is workable. I feel you have a problem while calling the method exclusiveMethod() you could check the instance by using instanceof and then call the method as below:

if (var instanceof Truck) {
    var.someMethod();
    ((Truck)var).exclusiveMethod();
} else {
    var.someMethod();
}
0
Alex Rogachevsky On

This is basic OOP polymorphism. Define an empty exclusiveMethod() in your superclass (Item) and then override it in Truck adding some code. You won't need any if statements 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();