类中,static修饰的成员变量为静态变量,方法为静态方法,生命周期与类相同,且从属于类。
#以下几点需要注意
1,静态方法不可以调用非静态方法,
2,普通方法可以调用静态方法
3,普通方法可以调用静态属性
/**
* static的用法
* @author lsd
*
*/
public class User2 {
int id;
String name;
String password;
static String str = "杭州西湖";
/**
* 两个参数的构造函数
* @param id
* @param name
*/
public User2(int id, String name) {
this.id = id;
this.name = name;
}
public static void printStr() {
System.out.println(str);
}
public static void main(String[] args) {
User2 u = new User2(101, "利达");
User2.printStr();
User2.str = "杭州西湖2";
User2.printStr();
}
}
静态块的理解和示例,静态块会在构造函数之前执行:
在这里插入代码片
```/**
* static静态块方法
* @author lsd
*
*/
public class User3 {
int id;
String name;
String pwd;
static String company;
public User3() {
System.out.println("构造函数");
}
static {
System.out.println("static静态块开始初始化");
company = "测试静态块";
printCompany();
}
public static void printCompany(){
System.out.println(company);
}
public static void main(String[] args) {
/**
* 类未创建,静态块就开始执行
*/
User3 u3 = new User3();
}
}`
static静态块和构造函数的执行顺序:
父类静态代码块->子类静态代码块->父类函数->父类构造函数->子类函数->子类构造函数
package com.test;
class Parent {
static String name = "hello";
{
System.out.println("父类函数");//3
}
static {
System.out.println("父类静态代码块");//1
}
public Parent() {
System.out.println("父类构造函数");//4
}
}
class Child extends Parent {
static String childName = "hello";
{
System.out.println("子类函数");//5
}
static {
System.out.println("子类静态代码块");//2
}
public Child() {
System.out.println("子类构造函数");//6
}
}
public class Test {
public static void main(String[] args) {
new Child();// 语句(*)
}
}
结果为:
父类静态代码块
子类静态代码块
父类函数
父类构造函数
子类函数
子类构造函数
# 静态方法重写注意点
静态方法重写的时候会编译不通过,因为静态方法可以通过对象去访问,所以本例中静态方法的示例其实是通过父类对象直接访问方法。
package com;
public class Test {
public static void main(String[] args) {
Father f = new Son();
//调用静态方法
f.method1();
//调用非静态方法
f.method2();
}
}
class Father{
public static void method1(){
System.out.println("我是父类的方法1。。。");
}
public void method2(){
System.out.println("我是父类的方法2。。。");
}
}
class Son extends Father{
public static void method1(){
System.out.println("我是子类的方法1。。。");
}
public void method2(){
System.out.println("我是子类的方法2。。。");
}
}
我是父类的方法1。。。
我是子类的方法2。。。