0

As in the title, I can't get to work a method in class A that is used in another class B to extend ArrayList. Here's my "mockup" code:

public class Claz{
    private String str;

    //Constructor
    public Claz(String str){
        this.str = str;
    }

    //get method
    public String getStr(){
        return this.str;
    }
}

Here's the ArrayList extension:

import java.util.*;

public class ClazList<Claz> extends ArrayList<Claz>{

    //ArrayList extension constructor: the parameter is a array of Claz
    public ClazList(Claz[] clazArray){
        for(int i = 0; i < clazArray.length; i++){
            this.add(clazArray[i]);
        }
    }

    //Print method that doesn't work
    public void printClaz(){
        for(int i = 0; this.size(); i++){
            System.out.println(this.get(i).getStr());
        }
    }
}

The compiler error is that the getStr() method is not found in Object class, but I don't even understand why it tries to find it there. The exact message is

error: cannot find symbol
Symbol:     method getStr()
location:   class Object

What am I doing wrong?

alemootasa
  • 83
  • 2
  • 9
  • 1
    When you write `public class ClazList` you are *declaring* generic type. It just happens that it has same name as already existing class, but it doesn't represent that class, it just shadows it. In other words your class declaration is same to `public class ClazList extends ArrayList` but `T` doesn't have `getStr()` method which is why you are seeing this error. You want `public class ClazList extends ArrayList{..}` – Pshemo Jun 02 '17 at 17:08
  • @Pshemo Wow, I didn't thought of it. This is actually a great feature, I didn't ever thought that you could declare a generic type. Thank you very much. Could you post your comment as a reply so I can accept that? I feel this is helpful to students like me that basically never have the need to use a custom generic type – alemootasa Jun 02 '17 at 17:14
  • "I didn't ever thought that you could declare a generic type" really? That is kind of counter-intuitive IMO since, well, they exist, so there must be some place where decision of their existence is made :) Anyway there are many other similar questions with already provided answers like: https://stackoverflow.com/q/35906893/1393766, problem is that to be able to find them you already need to know the answer (cause of the problem) which is generic type shadowing. That is why I marked your question as duplicate which also includes explanation of this case among others which cause this problem. – Pshemo Jun 02 '17 at 17:26

0 Answers0