JAVA基础篇(8)——【this调用属性,方法,构造方法】

 

Java关键字this只能用于各种方法方法(普通方法和构造方法)体内。当一个对象创建后,Java虚拟机(JVM)就会给这个对象分配一个引用自身的指针,这个指针的名字就是 this。但是在static修饰的静态方法中,是不允许使用this的,这里需要特别注意!

(1)this 调用属性

public class ThisDemo {  
    String name;
    int age;
    public ThisDemo(String name,int age){
        this.name="Mick";
        this.age=22;
    }   
  private void print(){
         System.out.println("最终名字="+this.name);
         System.out.println("最终的年龄="+this.age);
    }
    public static void main(String[] args) {
       ThisDemo t=new ThisDemo("",0); //随便传进去的参数
       t.print();
    }
}

输出:

最终名字=Mick
最终的年龄=22

 (2)this调用普通方法

/**
 * this调用普通方法
 * @author zxs
 *
 */
public class ThisDemo2 {
	String name;
	int age ;
	public ThisDemo2(String name,int age){
		this.name=name;
		this.age = age;
        //this调用普通方法
		this.print();	
	}
	public void print(){
		System.out.println("我是被this调用的方法打印出来的");
	}
	public String getInfo(){
		//this 调用本类属性
		 return "名字:"+this.name+"年龄"+this.age;
	}
	public static void main(String[] args) {
		ThisDemo2  t = new ThisDemo2("zhangxiansheng", 22);
		System.out.println(t.getInfo());
	}
}

 输出:

我是被this调用的方法打印出来的
名字:zhangxiansheng年龄22

(3)this调用构造方法

/**
 * this调用构造方法
 * @author 张勇
 *
 */
public class ThisDemo1 {
	int age;
	String name;
	int sex;
    //无参构造函数
	public ThisDemo1(){		
		System.out.println("无参构造方法");
	}
    //1参构造函数
	public ThisDemo1(int age){
		//用this调用无参构造函数,利用this语句的调用本类中的其他的构造函数必须位于第一句
		this();
		this.age=21;
		System.out.println("一个参数的构造方法");	
	}
    //2参构造函数
	public ThisDemo1(String name,int age){
		//this调用1参构造函数
                this(2);
		this.name="zhangxiansheng";		
		System.out.println("两个参数的构造方法");	
	}
    //3参构造函数
	public  ThisDemo1(String name,int age,int sex){
		this("zhang",2);
		this.sex=1;
		System.out.println("三个参数的构造函数");
	}
	public void print(){
		System.out.println("名字"+this.name);
		System.out.println("年龄"+this.age);
		System.out.println("性别"+this.sex);
	}	
	public static void main(String[] args) {
		ThisDemo1 t = new ThisDemo1("张先生", 21,1);
		t.print();		
	}
}

输出:

无参构造方法
一个参数的构造方法
两个参数的构造方法
三个参数的构造函数
名字zhangxiansheng
年龄21
性别1

注意:

(1)在调用构造方法时,被调用的构造方法只能放在本构造方法的第一行,例如:如果我们把 1参构造函数的this()方法放在下面,如下,就会报错。

(2)static静态方法不能使用this。

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值