码迷,mamicode.com
首页 > 其他好文 > 详细

this关键字

时间:2019-04-27 09:55:13      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:一个   要求   class   数据   其他   注意   col   关键字   nbsp   

问题: 存在着同名的成员变量与局部变量时,在方法内部默认是访问局部变量的数据,如何才能访问成员变量呢?


this关键字的作用:
1. 一个类存在着同名的成员变量与局部变量时,在方法内部默认是访问局部变量的数据,我们可以通过this关键字指定
访问成员变量的数据。

2. this关键字可以在构造函数中调用其他的构造函数初始化对象使用。


this关键字要注意的细节:
1. 如果在一个函数中访问一个成员变量,而且没有存在同名的局部变量 时,那么java编译器会默认在变量的前面加上this关键字的。
2. this关键字调用 其他的构造函数时,this语句必须 位于构造函数中的第一个语句。
3. this关键字调用构造函数的时候不准出现相互调用的情况,因为是一个死循环的调用方式。

 

需求: 编写java类描述一个动物。

class Animal{

    int id; // 编号
    
    String name;  //成员变量
    
    String color;  //颜色
        
    
    
    public Animal(int id,String name,String color){
        //this(); //调用了本类无参的构造函数。
        
        this(name,color); //调用到两个参数的构造函数
        this.id = id;
    }


    
    //构造函数
    public Animal(String name,String color){ //形式参数也是属于局部变量。
        this.name = name;
        this.color =color;
    }


    
    // this关键字代表的是所属函数的调用者对象。
    public void eat(){
        String name  = "猫";  //局部变量
        System.out.println(this.name+"在吃饭...");
    }

    public void sleep(){
        System.out.println(name+"在睡觉....");
    }

}


class Demo7{

    public static void main(String[] args) 
    {
        /*
        Animal a1 = new Animal();
        Animal a2 = new Animal();
        System.out.println("a1:"+ a1);
        System.out.println("a2:"+ a2);
        */


        Animal a1 = new Animal("哈巴狗","白色");    
        Animal a2 = new Animal(999,"沙皮狗","米黄色");
        //a1.sleep();
        
        System.out.println("名字:"+a1.name+" 颜色:"+ a1.color);
        System.out.println("编号:"+ a2.id+ " 名字:"+a2.name+" 颜色:"+ a2.color);
    }
}

需求:使用java类描述一个学生,学生有 name 、age两个属性, 还具备一个功能就是比较年龄。

要求:
1. 一旦创建了学生对象,学生就有了对应的属性值。 (构造函数、this)

//学生类
class Student{
    
    String name;

    int age;

    //构造函数
    public Student(String name,int age){ //存在同名的成员变量与局部变量。
        this.name = name;
        this.age = age;
    }

    //比较年龄    
    public void compareAge(Student s2){
        if(this.age>s2.age){
            System.out.println(this.name+"大");
        }else if(this.age<s2.age){
            System.out.println(s2.name+"大");
        }else{
            System.out.println("同龄....");
        }
    }
    

}

class Demo8 
{
    public static void main(String[] args) 
    {
        Student  s1  = new Student("张三",28);
        Student  s2  = new Student("王五",19);
        s1.compareAge(s2);
    }
}

 

this关键字

标签:一个   要求   class   数据   其他   注意   col   关键字   nbsp   

原文地址:https://www.cnblogs.com/hbxZJ/p/10777640.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!