JAVASE


随堂小笔记:

实例变量、实例方法、静态变量、静态方法

实例变量和方法要用 "引用."的方式进行访问、static方法要用 ""类名."的方式进行访问。


this使用方法01

this只能用于实例变量中不能用于static中、在实例方法中一般是默认含有this的、在构造方法中是不能省略的。

public class Test{
	String name;
	int id;
	//无参构造
	public Test(){
	}
	//有参构造
	public Test(String name; int id){
		this.name = name;
		this.id=id;
	}
	
}

this使用方法02

提示:this在以下代码提高了代码的复用率使得无参构造直接引用有参构造里面的变量。这是sun公司提供一套简单的构造方法调用别的构造方法,当然你自己在无参构造中写也是可以的。这样主要是方便了编程。

总结:this可以使用在哪里?

01 this可以使用在实例方法中,代表当前对象。语法格式为【this.】

02 this可以使用在构造方法中,通过当前构造方法去调用其他构造方法,语法格式【this(实参);】 重点:02的语法只能在构造方法中语句的首行 其他行报错;

public class Date {

    private int year;
    private int month;
    private int day;
    //调用无参构造和有参构造
    /*
    * 需求:在无参构造中默认创建对象的时候日期是1970.1.1
    * */
    //这种写法代码重复了 可以用更方便的写法写
    /*public Date() {
        year = 1970;
        month = 1;
        day = 1;
    }*/
    public Date(){
        //Date a =new Date();  这样是不可取的
        this(1970,1,1);
    }

    public Date(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }
    //调用setter和getter方法


    public void setyear(int year) {
        this.year = year;
    }

    public void setmonth(int month) {
        this.month = month;
    }

    public void setday(int day) {
        this.day = day;
    }

    public int getyear() {
        return year;
    }

    public int getmonth() {
        return month;
    }

    public int getday() {
        return day;
    }

    //调用显示日期的方法打印出来
    public void  printf(){
        System.out.println(this.year+"年"+this.month+ "月"+this.day+"日");
    }
}
class DateTset{
    public static void main(String[] args) {
        //创建对象1
        Date time1 = new Date();
        time1.printf();

        //创建对象2
        Date time2 = new Date(2008,8,8);
        time2.printf();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值