java面对对象学习笔记(static)

一、static修饰成员变量

1. 定义与特性
类变量:static修饰的成员变量称为类变量,属于类本身,而非某个具体对象。它在JVM加载类时初始化,存储在方法区(Method Area),所有对象共享同一份数据,生命周期与类一致。

package Staticdemo;

public class Student {
    //static修饰的对象,属于类,计算机里只有一份,被本类的所有对象共享
    static String name;
    //非static修饰的对象,属于对象,每个对象都有各自的age
    int age;
    int scorce;
}

2、访问方式 

(1)可以用类名.静态变量直接修改

(2)用变量名.静态变量访问,但不推荐

package Staticdemo;

public class Text {
    public static void main(String[] args)
    {
        Student s1=new Student();
        Student s2=new Student();
        //被static修饰的变量可以直接用类名.变量名修改,此时name为李华
        Student.name="李华";
    System.out.println(s1.name);
    System.out.println(s2.name);
    //都是李华
        //static修饰的变量可以用对象修改,但不推荐,这样改体现不出static变量的特殊性
        s1.name="张三";
        //此时两个结果都是张三
        System.out.println(s1.name);
        System.out.println(s2.name);
    }
}

3、应用场景

当某个数据只需要一份并且需要被共享时可以用static修饰变量(全局计数器)

package Staticdemo;

public class User {
    static int count=0;
    String name;
    int age;
    public User()     //运行无参构造器时count+1代表创建了一个变量
    {
        User.count++;//统计创建的对象的个数
    }
}
package Staticdemo;

public class Text {
    public static void main(String[] args)
    {
        
        //static修饰的变量应用场景,某个数据只需要一份且需要被共享
        User p=new User();
        User q=new User();
        System.out.println(User.count);//创建了两个对象(count统计创建对象的个数)
    }
}

二、static修饰方法

1、 定义与特性

类方法:static修饰的方法称为类方法,属于类而非对象,无需实例化即可调用

2. 访问限制

仅能访问静态成员:静态方法中不能直接访问实例变量或实例方法(因无this指针)

package Staticdemo;

public class Student {
    //static修饰的方法属于类,可以用类直接访问
    public static void HelloWorld()
    {
        System.out.println("Hello World");
        System.out.println("Hello World");
        System.out.println("------------");
    }
}

3、访问方式

可以用类名.方法名访问,也能用对象名.方法名访问(但不推荐,理由同上)

package Staticdemo;

public class Text2{
    public static void main(String[] args)
    {
        //static修饰的方法可以用类名直接访问
        Student.HelloWorld();
        Student s1=new Student();
        //也能用对象进行访问,但不推荐
        s1.HelloWorld();
    }
}

4、 应用场景

如果一个方法只是为了做一个功能而不需要访问对象内的数据,就可以直接用static修饰。

如果这个方法是对象的行为,需要访问对象内的数据,就不用static修饰。

package Staticdemo;

public class Student {
    //static修饰的对象,属于类,计算机里只有一份,被本类的所有对象共享
    static String name;
    //非static修饰的对象,属于对象,每个对象都有各自的age
    int age;
    int scorce;
    //没有static修饰的方法属于对象,只能用对象直接访问
    public void printpass()
    {
        if(scorce>=60)
            System.out.println("通过了");
        else
            System.out.println("没通过");
    }
}
package Staticdemo;

public class Text2{
    public static void main(String[] args)
    {

        //对象名.实例方法名访问方法
        s1.scorce=90;
        s1.printpass();
    }
}

注意事项:静态方法无this参数,因此不能用this。类变量可以就地初始化。

你可能感兴趣的:(java,学习,笔记)