+ 7
Generics , printing an objects field
Hi can anyone help explain why I cant print the field in my code it's not making sense to me đ€. https://code.sololearn.com/cw64KRdIGMgp/?ref=app
4 RĂ©ponses
+ 7
D_Stark I don't know much about Java, but I know generics from other languages. The thing is, `T extends Inhert` only tells the compiler that T has all the properties and methods that the `Inhert` class has. So the compiler doesn't know that T has a property `i` on it, because the class `Inhert` doesn't, and thus gives error.
One thing you can do is, on line 34, cast this.obj to `Program` and then access the property `i` on it. But this is ONLY possible when you are sure that T is of type `Program`. This works because when you cast, you are specifying the type of T. So change line 34 to
System.out.print(((Program) this.obj).i);
and it should work.
+ 4
Hi D_Stark,
Please find the Answer in comment.
https://code.sololearn.com/cNQS6vCi4G9p/?ref=app
Question shared by : Minho đ°đ·
đŸ Hope it will help you. đ
+ 1
XXX thanks theres always somthing with java that puzzles me lol
I'm thinking in my mind
T obj is really Program obj;
Then with the constructor I store the object ref in obj..
This is why I thought obj being the refrenece could point to its fields
+ 1
public class Program extends Inhert {
int i = 20;
public String toString(){
return super.toString() +"\ni = "+ i;
}
public static void main(String[] args) {
Test<Program> t = new Test<Program>(new Program());
t.print();
}
}