package com.hspedu.static_;
public class Course378 {
public static void main(String[] args) {
// 类方法/静态方法
/*
* 1、语法:
* 访问修饰符 static 返回类型 方法名() {...}
* static 访问修饰符 返回类型 方法名() {...}
*
* 2、类方法的调用:
* 类名.方法名
* 对象名.方法名
* (前提是满足访问权限)
* */
Student tom = new Student("tom");
tom.payFee(100);
tom.showFee();
Student mary = new Student("mary");
mary.payFee(200);
mary.showFee();
Student.payFee(1000);
Student.showFee();
}
}
class Student {
private String name;
// 定义静态变量统计学费
private static double fee = 0;
public Student(String name) {
this.name = name;
}
// 静态方法
public static void payFee(double fee) {
Student.fee += fee;
}
public static void showFee() {
System.out.println("总学费有:" + Student.fee);
}
}
package com.hspedu.static_;
public class Course380 {
public static void main(String[] args) {
// 静态方法细节
/*
* 1、普通的成员方法不能通过类名调用,静态方法可以
* 2、静态方法不能使用this和super
* 3、静态方法(类方法)只能访问静态变量和静态方法(静态方法只能访问静态成员)
* 4、普通的方法,既可以访问非静态成员,也可以访问静态成员
* */
// MyTools.say();
new MyTools().say();
MyTools.hi();
MyTools.hello();
}
}
class MyTools {
private int n1 = 100;
private static int n2 = 200;
// 普通成员方法
public void say() {
System.out.println("say" + this.n2);
}
// 静态方法
public static void hi() {
// 静态方法里不能用this,也不能调用普通的成员变量
// System.out.println(this.n1);
// System.out.println(n1);
// System.out.println(this.n2);
System.out.println(n2 + ", " + MyTools.n2 + ", hi");
}
// 静态方法只可以调用静态成员,并且不能使用this
public static void hello() {
// this.hi();
// say();
hi();
}
// 一般的成员方法都可以调用静态、非静态成员
public void ok() {
System.out.println(n1 + ", " + n2);
say();
hello();
}
}