this与static关键字的用法

导读:本篇文章讲解 this与static关键字的用法,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

一、this

1、this.属性名
一个方法当中的局部变量和成员变量名称相同,我们的程序需要在这个方法当中访问成员变量,这个时候就必须使用this关键字,用来区分成员变量和方法当中的参数。例如,set方法

 	private int age;
    public void setAge(int age) {
        this.age = age;
    }

2、this.方法名
让类中的一个方法来访问类中的另一个方法或者实例变量

public class Test {
    public static void main(String[] args){
        Test test = new Test();
        test.function();
    }
    public void function(){
        this.run();
    }
    public void run(){
        System.out.println("hello world");
    }
}
hello world

3、this()
this()可以用来访问本类的构造方法
①this()不能在普通方法中使用,只能在构造方法中使用
②this()在构造方法中使用必须是第一条语句
③在一个类下两个构造方法中不能通过this()相互调用
④不能与super()同时使用

public class Cat {
    private String name;
    private int age;
    public Cat(String name, int age) {
        this.name = name;
        this.age=age;
    }
    public Cat(){
        this("大橘",3);
    }
    public String toString() {
        return name+" "+age;
    }
    public static void main(String[] args) {
        Cat cat=new Cat();
        System.out.println(cat.toString());
    }
}
大橘 3

二、static

1、静态块在构造方法前执行,静态块只执行一次,只能由当前类的第一个对象触发执行,同级别要等上面的执行完才会执行下面的。

public class Demo1 {
    public Demo1(){
        System.out.println("构造方法");
    }
    {
        System.out.println("非静态1");
    }
    {
        System.out.println("非静态2");
    }
    static{
        System.out.println("静态1");
    }
    public static Demo1 demo=new Demo1();
    static{
        System.out.println("静态2");
    }
}
public class Test {
    public static void main(String[] args) {
        Demo1 demo1=new Demo1();
        Demo1 demo2=new Demo1();
    }
}
静态1
非静态1
非静态2
构造方法
静态2
非静态1
非静态2
构造方法
非静态1
非静态2
构造方法

2、static修饰的变量属于类变量,被所有对象共享

public class Cat {
    static String name;
    int age;
    public Cat(String name,int age) {
        this.name = name;
        this.age=age;
    }
    public String toString() {
        return name+" "+age;
    }
}
public class Test {
    public static void main(String[] args) {
        Cat cat1=new Cat("cat1",12);
        Cat cat2=new Cat("cat2",18);
        System.out.println(cat1.toString());
        System.out.println(cat2.toString());
    }
}
cat2 12
cat2 18

3、static关键字的作用

  • 方便在没有创建对象的时候对方法和变量进行调用
  • static修饰的代码块,在main方法之前执行,以便于优化程序

4、static关键字使用时需注意

  1. this关键字不能在static方法当中使用
  2. static修饰的方法属于类方法(静态方法),静态方法当中不能使用非静态的方法,非静态的方法能够使用静态方法

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/71551.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!