zoukankan      html  css  js  c++  java
  • This的关键字的使用

    this:

      1.可以用来修饰属性  方法 构造器

      2.this理解为当前对象或当前正在创建的对象、

      3.可以在构造器中通过this()形参的方式显示的调用本类中其他重载的指定的构造器

            要求: 在构造器内部必须申明在首行

                        若一个类中有n个构造器, 那么最多只能有  n-1 个构造器中使用  this(形参)

    public class TestPerson {
    
    }
    
    class Person {
        private String name;
        private int age;
    
        public Person(String n) {
            name = n;
        }
    
        public Person(String n, int a) {
            name = n;
            age = a;
        }
    
        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 eat() {
            System.out.println("c吃饭");
        }
    
        public void sleep() {
            System.out.println("睡觉");
        }
    
        public void info() {
            System.out.println("name:" + name + "age:" + age);
        }
    
        public void show() {
            System.out.println("a苗苗");
        }
    }

     例:编写两个类.TriAngle和TestTriAngle,其中TriAngle中声明私有的底边长base和高height

            同时声明公共的方法访问私有变量,另一个类中使用这些公共方法,计算三角形的面积。

    public class TestTriAngle {
        public static void main(String[] args) {
            TriAngle t = new TriAngle();
            t.setBase(2.3);
            t.setHeight(1.2);
            t.findArea();
            System.out.println("面积为:" + t.findArea());
        }
    
    }
    
    class TriAngle {
        private double base;
        private double height;
    
        public TriAngle() {
            this.base = 1.2;
            this.height = 1.2;
        }
         //this.base 表示当前正在创建的对象
        //base 为形参
        public TriAngle(double base, double height) {
            this.base = base;
            this.height = height;
        }
    
        //this.base 表示当前对象的属性
        //base 为形参
        public double getBase() {
            return base;
        }
    
        public void setBase(double base) {
            this.base = base;
        }
    
        public double getHeight() {
            return height;
        }
    
        public void setHeight(double height) {
            this.height = height;
        }
    
        public double findArea() {
            return this.base * this.height / 2;
        }
        
        
    }

    输出结果:
    面积为:1.38
    All that work will definitely pay off
  • 相关阅读:
    Java8简单的本地缓存实现
    Java堆内存详解
    拖拽实现备忘:拖拽drag&拖放drop事件浅析
    微信小程序下拉刷新PullDownRefresh的一些坑
    ES6里let、const、var区别总结
    nodejs大文件分片加密解密
    node+js实现大文件分片上传
    大文件上传前台分片后后台合并的问题
    fs.appendFileSync使用说明,nodejs中appendFile与writeFile追加内容到文件区别
    JS中的单线程与多线程、事件循环与消息队列、宏任务与微任务
  • 原文地址:https://www.cnblogs.com/afangfang/p/12501009.html
Copyright © 2011-2022 走看看