Setter and getter question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Setter and getter question

why is this setter and getter code doesnt print "electric"? class Myclass{ public static void main(String[]args){ Pokemon.settype("electric"); System.out.println(Pokemon.gettype()); } } class Pokemon{ private String type; static void settype(String t){ this.type=t; } static String gettype(){ return type; } }

18th Oct 2017, 1:54 AM
oyl
3 Answers
+ 11
You shouldn't use static for both the getter and setter as each Pokemon have different types, making it static means they all share the same properties. Here's a proper way to do it, or better still, use a constructor to set it:- https://code.sololearn.com/c46lUlWoXGwL/?ref=app Hopefully it helps! 😉
18th Oct 2017, 2:57 AM
Zephyr Koo
Zephyr Koo - avatar
+ 1
@Gordie what do you mean by that?can u explain pls
18th Oct 2017, 6:54 AM
oyl
+ 1
@Gordie it can run now after i add static to type class Myclass{ public static void main(String[]args){ Pokemon.settype("electric"); System.out.println(Pokemon.gettype()); } } class Pokemon{ private static String type; static void settype(String t){ type=t; } static String gettype(){ return type; } }
18th Oct 2017, 7:25 AM
oyl