简体   繁体   中英

Java using interface as data type

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

在此处输入图像描述

I would appreciate an explanation on how to solve this.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM