1. class variable is static
public class demo{
public static void Main (string[] args) {
Child ch1 = new Child (3, "Niuniu");
Ch1.joingame ();
Child CH2 = new Child (4, "small");
Ch2.joingame ();
Child CH3 = new Child (5, "big");
Ch3.joingame ();
SYSTEM.OUT.PRINTLN ("total =" +child.total);
}
}
Class child{
int age;
String name;
static int total=0;
Public child (int age,string name) {
This.age=age;
This.name=name;
}
public void Joingame () {
total++;
}
}
2. class method
public class demo{
public static void Main (string[] args) {
Stu stu1 = new Stu ("AA", 340);
Stu STU2 = new Stu ("BB", 240);
System.out.println (Stu.gettotalfee ());
}
}
Class stu{
int age;
String name;
int fee;
static int totalfee;
Public Stu (int age,string name,int fee) {
This.age = age;
THIS.name = name;
Totalfee+=fee;
}
public static int Gettotalfee () {//This is a static method
return totalfee;
Age ++;//wrong,
}
}
Static Statics methods can access static static variables, cannot access non-static variables, and non-static methods can access both statically and non-static variables.
Hanshunping Java Note 8th Lecture this class variable 9th lecture class method