+ 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

14th Jan 2021, 2:02 PM
D_Stark
D_Stark - avatar
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.
14th Jan 2021, 3:13 PM
XXX
XXX - avatar
+ 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. 🙂
15th Jan 2021, 5:47 AM
P∆WAN M∆URY∆
P∆WAN M∆URY∆ - avatar
+ 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
14th Jan 2021, 3:55 PM
D_Stark
D_Stark - avatar
+ 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(); } }
14th Jan 2021, 6:58 PM
zemiak