我是靠谱客的博主 想人陪酒窝,最近开发中收集的这篇文章主要介绍this与static关键字的用法,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

一、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修饰的方法属于类方法(静态方法),静态方法当中不能使用非静态的方法,非静态的方法能够使用静态方法

最后

以上就是想人陪酒窝为你收集整理的this与static关键字的用法的全部内容,希望文章能够帮你解决this与static关键字的用法所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(49)

评论列表共有 0 条评论

立即
投稿
返回
顶部