zoukankan      html  css  js  c++  java
  • this关键字

    -----------siwuxie095

       

       

       

    this 关键字:

       

    (1)表示类中的属性和调用方法

       

    2)表示本类中的构造方法

       

    3)表示当前对象

       

       

       

    代码1

       

    package com.siwuxie095.thisdemo;

       

    class People{

    private String name;

    private int age;

     

    public People(String name,int age) {

    //代表构造方法,且必须放在首行,否则无法通过编译

    this();

    this.name=name;

    this.age=age;

    }

     

    public People() {

    System.out.println("无参构造方法");

    }

     

    public String getName() {

    return name;

    }

    public void setName(String name) {

    this.name = name;

    }

    public int getAge() {

    return age;

    }

    public void setAge(int age) {

    this.age = age;

    }

     

    public void tell() {

    System.out.println("姓名:"+this.getName()+" 年龄:"+this.getAge());

    }

     

    }

       

    public class ThisDemo01 {

       

    public static void main(String[] args) {

    People p=new People("张三",30);

    p.tell();

    }

       

    }

       

       

    运行一览:

       

       

       

       

    代码2

       

    package com.siwuxie095.thisdemo;

       

    class PeopleX{

     

    public void tell() {

    //this 表示当前对象

    System.out.println(this);

    }

    }

       

    public class ThisDemo02 {

       

    public static void main(String[] args) {

    PeopleX p=new PeopleX();

    //输出一致,可以通过这种方式比较两个对象是不是同一对象

    System.out.println(p);

    p.tell();

    }

       

    }

       

       

    运行一览:

       

       

       

       

       

       

    【made by siwuxie095】

  • 相关阅读:
    旋转数组的最小数字(JAVA)
    两个队列实现栈&两个栈实现队列(JAVA)
    重建二叉树(JAVA)
    二维数组的查找(JAVA)
    Java垃圾回收机制概述
    前端开发环境
    Java语法糖 : try-with-resources
    立个Flag (20180617-20181231)
    关于标签的整理
    Java反射机制
  • 原文地址:https://www.cnblogs.com/siwuxie095/p/6561997.html
Copyright © 2011-2022 走看看