Static关键字

类中,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。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值