黑马程序员学JavaDay1(Static)

1.修饰成员变量(类变量)

public class Student{
    String name;  //实例变量,由每个对象所有
    static int age;//类变量,由类所有
}

public class Test{
    public static void main(String[] args){
    Student.age=10;
    //通过类名调用age

    Student s1=new Student();
    System.out.println(s1.age);
    //通过对象名调用age

     Student s2=new Student();
    System.out.println(s2.age);
    }
}

s1,s2有相同的age

好处:只占一份内存,且可以被共享

public class User{
    public static int number;

    public User(){
    User.number++;
    }

}


public class test{
    public static void main(String[] args){
    
    User u1=new User();
    System.out.println(User.number);

    }
}

2.修饰成员方法(类方法)

public class Student{
    String name;

//类方法
    public static void hello(){
    System.out.println("hello");
    }


//实例方法
    public void printname(){
        System.out.println(this.name);
    }

}


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

    Student.hello();//通过类名调用类方法
    
    Student s1= new Student();
    s1.name="John";

    Student s2= new Student();
    s2.name="kim";

    s1.hello();//通过对象调用类方法
    s1.printname();//调用实例方法
    s2.printname();
    }

}

类方法的好处:提高代码复用性

代码块

public class Student {
    String name;
    static int age;

    //静态代码块
    //初次加载类时执行,只执行一次
    static{
        System.out.println("静态代码块执行了~");
        age = 18;
    }

    //实例代码块
    //构造对象时先执行,再构造对象
    {
        System.out.println("实例代码块执行了~");
        System.out.println(this.age);
    }

    Student(){
        System.out.println("无参数构造器执行了");
    }
    Student(String name){
        System.out.println("有参数构造器执行了");
        this.name = name;
        System.out.println(this.name);
    }

}

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

     Student s1= new Student();
     Student s2= new Student("kim");
        }
    }
}

main方法

注意事项

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值