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; } }
6 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! đ
+ 1
@Gordie what do you mean by that?can u explain pls
+ 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;
}
}