A metaphorical or really clear explanation about the usage of static variables or methods in java -
i've asked teacher thousand times , explained me many times, still don't when use static in variables/methods
could give metaphorical explanation this, maybe showing examples static needed , not?
do want access method without instance of class?
if answered yes, want static method.
private static variables can used share data across instances of class, i.e. if have:
public class car { private static int wheelsnum; private string company; private string color; ... ... }
then if change wheelnum
2, cars have 2 wheels.
for example, consider piece of code:
car car1 = new car(); car car2 = new car(); car1.setcolor("yellow"); car2.setcolor("blue"); car1.setwheelsnum(4); car2.setwheelsnum(2);
then both cars have 2 wheels, although "didn't" mean change wheels number of first car. but, can tell, cars have different colors.
public static
variables used without making instance of class, wheras private static
variables not.
when need use variable in static function, can use static variables, making private not access them other classes.
static methods can't access non-static methods (and same variables).
Comments
Post a Comment