java学习第十五章(Static关键字)

static 关键字:(用来修饰成员变量和方法)

类的成员

成员变量

  • 实例成员变量(必须通过对象名.属性名)
  • 静态变量(使用static来修饰的变量为静态变量)

方法

  • 实例方法(必须通过对象名.方法名())
  • 静态方法(使用static来修饰的方法为静态方法)
    PS 静态方法中无法使用实例变量
演示效果!
class Student {
    String name;// 这是一个成员变量
    static float height;// 定义一个静态变量
    // static定义一个静态方法
    public static void show() {
        //System.out.println("身高:" + height); 会报错因为静态方法中无法使用实例变量
        System.out.println("我是一个静态方法!");
    }
}
public class ThisAndStatic {
    public static void main(String[] args) {
        Student s1 = new Student ()
        // static定义的静态变量height
        St.height = 175.3F;// 赋值:类.静态变量名 = 值
        System.out.println("身高:" + St.height);// 访问: 类.静态变量名
         // System.out.println("身高:" + s1.height); // 不建议使用实例访问
        St.show();
         // s1.show(); // 不建议使用实例访问
    }
}
// => 身高:175.3
// => 我是一个静态方法!

PS
静态变量不能用实例对象赋值必须用类.静态变量名的方式赋值。
静态方法无法访问类的成员变量。

我们做个简单的算术工具类
  • 工具类自带一个判定两个数字大小的方法
不使用static
class MathTools {
    public int max(int a, int b) {
        int c;
        c = a > b ? a : b;// a大于b就返回a,否则返回b。
        return c;
    }
}
public class ThisAndStatic {
    public static void main(String[] args) {
        // 调用一个工具类
        MathTools mt = new MathTools();
        int max = mt.max(2, 4);
        System.out.println("最大值是:" + max);
    }
}
// => 4
使用static
class MathTools {
    public static int max(int a, int b) {
        int c;
        c = a > b ? a : b;// a大于b就返回a,否则返回b。
        return c;
    }
}
public class ThisAndStatic {
    public static void main(String[] args) {
        int max = MathTools.max(2, 4);
        System.out.println("最大值是:" + max);
    }
}
// => 4
上一章 目录 下一章

你可能感兴趣的:(java学习第十五章(Static关键字))