简体   繁体   中英

Why couldn't I deal with argument in java?

I'm java virgin. I've made really simple code like below.

class TreeData implements Comparable<TreeData> {
    private String sixString;
    private ArrayList<Integer> stringNum = new ArrayList<Integer>();
    private ArrayList<Integer> charNum = new ArrayList<Integer>();

    public TreeData(String sixString, int stringNum, int charNum){
        this.sixString = sixString;
        (this.stringNum).add(stringNum);
        (this.charNum).add(charNum);
    }

    public int compareTo(TreeData other) {
        return sixString.compareTo(other.getSixString());
    }

    public String getSixString(){
        return sixString;
    }
}



class Child<T extends Comparable<T>>{
    public void print(T data){
        //error : String a = data.getSixString();
        System.out.println("hi");
    }
}


public class Test {
    public static void main(String[] args) {
        Child<TreeData> child = new Child<TreeData>();
        TreeData td = new TreeData("sixString", 8, 2);
        child.print(td);
    }
}

I had a problem in 'print' method in the Child class. When I tried calling the getSixString() method of data(passed as argument), it occurs error. I don't know why I can't using public method in the argument 'data'. Is it related with Generic? Thanks, in advance.

In your Child class, you only define T to be extending Comparable. Yet you expect it to have the method getSixString which Comparable doesn't have. What you probably want it for it to be extending TreeData:

class Child<T extends TreeData>{
    public void print(T data){
        String a = data.getSixString();
        //should work now since T defines getSixString()
    }
}

Or better yet if all you want is for T to be TreeData, you don't need any generic class. I'm assuming your real intention was:

class Child extends TreeData {
    public void print(){
        String a = getSixString();
    }
}

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