0

Is it possible to access to field or function of a class object that implements an interface using interface object?

for example:

public interface Node { // reference to all my trucks

    void collect(Package p);
    void deliver(Package p);
    void work();

}

public class Truck implements Node{...} 
public class Van extends Truck {...}

public class Tracking {

    private Node node;

    @Override
    public String toString() {
        return "time:" + time + " " + node + ", status=" + status;
    }
}

And from another class I try to print Tracking and get node to be specific function from Van class but instead the node return only the toString of the van function. And I have no access to other functions.

    for (int i = 0; i < this.tracking.size(); i++) {
        System.out.println(this.tracking.get(i));
    }

The main problem to access to the truckID field

enter image description here

I would appreciate an explanation on how to solve this.

1
  • As you use a println the default toString is called, but you can try to explicitly call another method yes Commented Mar 28, 2021 at 9:12

2 Answers 2

2

You can use instanceof to find the real class of the object, to be able to use its specific methods

for (Tracking track : this.tracking) {
    if (track instanceof Van){
        Van v = (Van) track;
        v.methodOfVan();
        System.out.println(v.truckID);
    }
    else if (track instanceof Truck ){ // For any other Truck that isn't Van
        Truck t = (Truck) track;
        t.methodOfTruck();
        System.out.println(t.truckID);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Mention that he needs to cast to the specific type to use methods on that type.
0

You are using inheritance here. Node is the super class. And inside your code, you are having a Node instance. That Node instance can be assigned to any subclass variable like a Van object.

Your question is why van specific method is not available in Node variable. See at compile time, Java complier won't know what type of subclass will get assigned into the Node variable. Suppose you have a Taxi class just like Van. So a Taxi object can be assigned to Node class. As this runtime information is not available to a compiler, it will make sure Node variable can access only Node specific fields.

If you know that only Van can be assigned to the Node variable, you can do a explicit casting.

Van van = (Van) node;

Then you can access van specific fields or methods. Compiler won't complain here as the coder has explicitly taking care of the class casting, so responsibility lies with the coder.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.