this关键字和static

this用于普通方法:指向调用该方法对象
this用于构造器:指向正要初始化对象
this()调用其它构造方法
this不能用于static方法

/**
 * 测试this隐式参数
 * @author 1376417539
 *
 */
public class Testthis {
    String name;
    int id;

    public Testthis(String name , int id) {
        this();             //通过this调用其它构造方法
        this.name = name;   //指向上面定义的String name,并初始化
        this.id = id;       //同理
        System.out.println(name + "会打针" + "编号是:" + id);
    }

    public Testthis() {
        System.out.println("我是医生。");// TODO Auto-generated constructor stub
    }

    public static void main(String[] args) {    
        Testthis doc = new Testthis("张三",1);    
    }
}
/**
 * output:我是医生。
 *           张三会打针编号是:1
 */

static(静态)方法中不能使用this关键字,在静态方法内部不可以调用非静态方法(并非完全不可以),反过来可以,并且可以在不创建对象的情况下直接通过类本身调用static方法。

public class Teststatic {
    public static void main(String[] args) {
        PrintTest1("调用静态方法。");
    }

    static void PrintTest1(String s) {
        System.out.println(s);
    }
}
/**
 * output:调用静态方法。
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值