java static
package cn.sasa.demo3;
public class Person {
//static 静态的
//静态成员属于类,是所有对象的共性,不是某个对象独有的,
//一个对象对其赋值之后,其他对象的也跟着变
//静态优先于非静态,类加载时,先将静态成员加载到方法区
public static String country;
public static void sayHi() {
System.out.println("hi");
}
}
package cn.sasa.demo3;
public class Student extends Person {
public static String school;
//常量:被final修饰的变量为常量
//静态常量:
public static final String LOCAL = "13512";//变量使用大写字母
//静态方法
public static void sayHi() {
System.out.println("stu hi");
}
}
package cn.sasa.demo3;
public class Test {
public static void main(String[] args) {
Person p = new Student();
Person p1 = new Person();
Student.country = "China";
System.out.println(Student.country);
//当其中一个对象修改了静态成员,其它的也跟着变
//静态成员是属于类的,是所有的这个类的对象的共性
p.country = "England";//不推荐这种调用方式
System.out.println(p1.country);
//静态中,编译看父类,运行也看父类,如果父类中没有此方法,则报错,
//运行时,运行的也是父类的方法
//因为静态方法是跟着类的,和对象没有关系
p.sayHi();//不推荐这种调用方式
//Student.LOCAL = "";//不允许赋值
//静态常量的调用
System.out.println(Student.LOCAL);
}
}
和C#不同,static不能用来修饰类


浙公网安备 33010602011771号