• Java面向对象--this关键字


    this 关键字

    this:当前类的对象
    this 可以在方法内获取到对象中的属性信息
    this 还可以区分局部变量和成员变量
    
    public class Car {
    	String color;
    	int speed;
    	int seat = 5;
    	
    	public void run() {
    	//默认会有一个this: 当前正在执行这个方法的对象
    	System.out.println(this);
    	System.out.println(this.color);
    	System.out.println(this.speed);
    	//获取到车的颜色和速度
    		System.out.println("车能跑");
    	}
    	
    	public void fly() {
    		System.out.println(this.color + "颜色的车会飞");
    		System.out.println(color + "颜色的车会飞");//  此时访问的也是成员变量
    		//变量的查找顺序:先找自己方法内,如果自己没有,就去this里面找
    	}
    	
    	public static void main(String[] args) {
    	/*
    		Car c = new Car(); // 车中的属性就是类中定义好的成员变量
    		c.color = "红色”;
    		c.speed = 120;
    		
    		// 在调用方法的时候,java会自动的把对象传递给方法,在方法中由this来接收对象
    		c.run(); 
    		//System.out.println(c);
    		
    		Car c2 = new Car();
    		c2.color = "绿色";
    		c2.speed = 180;
    		c2.run();
    	*/
    		//this 可以帮我们区分成员变量和局部变量
    		Car c = new Car();
    		c.color = "绿色";
    		
    		c.fly("黑色");
    	}
    }
    
    
    
    
    
  • 相关阅读:
    GitLab 重置认证和添加账号缓存
    PHP 正则匹配IP
    git 删除指定版本
    PostgreSQL 9.2 日期运算
    postgre 已有字段修改为自增
    postgresql 导入导出
    PHP TS 和 NTS 版本选择
    background-image属性的设置
    SQLServer 附加数据库后只读或报错解决方法
    IIS 6.0 发布网站使用教程
  • 原文地址:https://www.cnblogs.com/isChenJY/p/12726990.html
Copyright © 2020-2023  润新知